2012-08-16 30 views
6

.NET名前空間が提供するWebClientオブジェクトを介してFTPサーバーからファイルをダウンロードしてから、実際のファイルにBinaryWriterで書き込んでいます。すべてが良いです。しかし、今、ファイルのサイズが劇的に増加しています。私はメモリの制約があるので心配しています。ダウンロードストリームを作成し、ファイルストリームを作成し、ダウンロードから読み込んでファイルに書きたいと思います。FTPからローカルストレージにファイルをダウンロードする

私はこの素晴らしい例を見つけることができなかったので、私は緊張しています。ここに私の最終結果があります:

var request = new WebClient(); 

// Omitted code to add credentials, etc.. 

var downloadStream = new StreamReader(request.OpenRead(ftpFilePathUri.ToString())); 
using (var writeStream = File.Open(toLocation, FileMode.CreateNew)) 
{ 
    using (var writer = new StreamWriter(writeStream)) 
    { 
     while (!downloadStream.EndOfStream) 
     { 
      writer.Write(downloadStream.ReadLine());     
     } 
    } 
} 

私はこの不適切な/より良い方法/などについてはありますか?

答えて

8

WebClientクラスの次の使用を試しましたか?

using (WebClient webClient = new WebClient()) 
{ 
    webClient.DownloadFile("url", "filePath"); 
} 

更新

using (var client = new WebClient()) 
using (var stream = client.OpenRead("...")) 
using (var file = File.Create("...")) 
{ 
    stream.CopyTo(file); 
} 

あなたは、カスタマイズされたバッファサイズを使用して明示的にファイルをダウンロードする場合:はい

public static void DownloadFile(Uri address, string filePath) 
{ 
    using (var client = new WebClient()) 
    using (var stream = client.OpenRead(address)) 
    using (var file = File.Create(filePath)) 
    { 
     var buffer = new byte[4096]; 
     int bytesReceived; 
     while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0) 
     { 
      file.Write(buffer, 0, bytesReceived); 
     } 
    } 
} 
+0

、まだ(requestオブジェクトがWebクライアントで午前[I」は私のポストを更新してこれを明示的に表示する])しかし、DownladFileはメモリ内のファイル全体を私が探しているものの反対に与えるでしょう。 – OnResolve

+0

@OnResolve、申し訳ありません、私はしていませんと述べた。アップデートをご覧ください。 –

+0

@OnResolve、カスタマイズしたバッファーサイズのバージョンを追加しました。 –

関連する問題