1

次のコードを使用して、Windows サービスを使用して FTP ホストからデータを取得しています。

私たちは呼んでいます

DownloadFile("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 に答える