使用FTP客户端下载,服务与大文件崩溃

时间:2012-06-06 14:02:29

标签: c# windows-services ftp bytearray

我使用以下代码使用Windows服务从FTP主机获取数据。

我们正在打电话

DownloadFile( “movie.mpg”, “C:\电影\”)

    /// <summary>
    /// This method downloads the given file name from the FTP server
    /// and returns a byte array containing its contents.
    /// </summary>
    public byte[] DownloadData(string path, ThrottledStream.ThrottleLevel downloadLevel)
    {
        // Get the object used to communicate with the server.
        WebClient request = new WebClient();

        // Logon to the server using username + password
        request.Credentials = new NetworkCredential(Username, Password);

        Stream strm = request.OpenRead(BuildServerUri(path));
        Stream destinationStream = new ThrottledStream(strm, downloadLevel);
        byte[] buffer = new byte[BufferSize];
        int readCount = strm.Read(buffer, 0, BufferSize);

        while (readCount > 0)
        {
            destinationStream.Write(buffer, 0, readCount);
            readCount = strm.Read(buffer, 0, BufferSize);
        }

        return buffer;
    }

    /// <summary>
    /// This method downloads the given file name from the FTP server
    /// and returns a byte array containing its contents.
    /// Throws a WebException on encountering a network error.
    /// Full process is throttled to 50 kb/s (51200 b/s)
    /// </summary>
    public byte[] DownloadData(string path)
    {
        // Get the object used to communicate with the server.
        WebClient request = new WebClient();

        // Logon to the server using username + password
        request.Credentials = new NetworkCredential(Username, Password);

        return request.DownloadData(BuildServerUri(path));
    }

    /// <summary>
    /// This method downloads the FTP file specified by "ftppath" and saves
    /// it to "destfile".
    /// Throws a WebException on encountering a network error.
    /// </summary>
    public void DownloadFile(string ftppath, string destfile)
    {
        // Download the data

        byte[] Data = DownloadData(ftppath);



        // Save the data to disk
        if(!System.IO.Directory.Exists(Path.GetDirectoryName(destfile)))
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(destfile));
        }
        FileStream fs = new FileStream(destfile, FileMode.Create);
        fs.Write(Data, 0, Data.Length);
        fs.Close();
    }

当我达到500mb左右时,我的软件一直崩溃,当PC的字节数组/内存耗尽时(我只有1gb),我认为它正在崩溃。任何人都知道我可以将数据作为临时文件直接写入磁盘而不是存储在字节数组中。下载完成后,基本上将临时文件移动到新位置。

1 个答案:

答案 0 :(得分:0)

您可以直接写入以下内容:

using (Stream stream = request.GetRequestStream())
{
    stream.Write(file.Data, 0, file.Data.Length);
}