1

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

我们在打电话

下载文件("movie.mpg","c:\movies\")

    /// <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)。任何人都知道我可以将数据作为临时文件直接写入磁盘而不存储在字节数组中的方法。下载完成后,基本上将临时文件移动到新位置。

4

1 回答 1

0

you can write directly to the stream something like the below:

using (Stream stream = request.GetRequestStream())
{
    stream.Write(file.Data, 0, file.Data.Length);
}
于 2012-06-06T14:07:14.233 回答