2012-10-10 32 views
-3

我正在嘗試將所有字節下載到3個不同的文件中,現在我正在使用WebRequest和WebResponse對象。我相信它的正確方法? 我被困在寫數據的部分文件中。不管寫什麼數據,目前的目標是從同一個流中讀取數據並將其寫入3個不同的文件。 我可以寫成第一個文件,比它給出的錯誤 - 當我嘗試將流(我從response.getResponseStream()獲得)分配給另一個binaryreader時,流不可讀。如何將下載的數據寫入多個文件?

我試過了兩種方法 - 一種是直接將responsestream傳遞給不同的binaryreaders,失敗。 其次,我試圖爲每個binaryreader創建separte引用,但也失敗了。 這裏是代碼,如果它能夠幫助: -

using (Stream strm = res.GetResponseStream()) 
{ 
    using (Stream strm1 = strm) 
    { 
     int i = 0; 
     BinaryReader br = new BinaryReader(strm1); 
     br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
      new AsyncCallback(ProcessDnsInformation), br); 
     Console.WriteLine("Data read {0} times", i++); 
     Console.ReadKey(); 
     File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish.bin", buffer); 
     br.Close(); 
    } 

    using (Stream strm2=strm) 
    { 
     int i = 0; 
     BinaryReader br = new BinaryReader(strm2); 
     br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
      new AsyncCallback(ProcessDnsInformation), br); 
     Console.WriteLine("Data read {0} times", i++); 
     Console.ReadKey(); 
     File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish1.bin", buffer); 
     br.Close(); 
    } 

    using (Stream strm3 = strm) 
    { 
     int i = 0; 
     BinaryReader br = new BinaryReader(strm3); 
     br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
      new AsyncCallback(ProcessDnsInformation), br); 
     Console.WriteLine("Data read {0} times", i++); 
     File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish2.bin", buffer); 
     br.Close(); 
    } 
} 

我學習C#,請忽略一些(或全部)愚蠢的編碼。

+0

因爲'Console.ReadLine()'你可能想要解決這個問題,所以你的代碼不是異步的。您也沒有發佈所有必需的代碼來幫助您,您遺漏了'ProcessDnsInformation',這非常重要。 –

回答

5

您至少有兩個問題。首先,看看這個:

using (Stream strm = res.GetResponseStream()) 
{ 
    using (Stream strm1 = strm) 
    { 
     ... 
    } 

只要你退出內部塊,流將被佈置 - 所以在接下來的塊,你不能從中讀出。

其次,你打電話BeginRead這是會開始讀取數據 - 但你已經完全分離回調從當你決定所有數據的時間。我會強烈建議您先使用同步IO,然後在適當的情況下移至異步IO。

相關問題