2012-05-19 56 views
0

为什么从WebClient流中读取时如何丢失字节?从WebClient流中读取时丢失字节

const int chuckDim = 80; 

System.Net.WebClient client = new System.Net.WebClient(); 
Stream stream = client.OpenRead("http://media-cdn.tripadvisor.com/media/photo-s/01/70/3e/a9/needed-backup-lol.jpg"); 
//Stream stream = client.OpenRead("file:///C:/Users/Tanganello/Downloads/needed-backup-lol.jpg"); 

//searching file length 
WebHeaderCollection whc = client.ResponseHeaders; 
int totalLength = (Int32.Parse(whc["Content-Length"])); 
byte[] buffer = new byte[totalLength]; 

//reading and writing 
FileStream filestream = new FileStream("C:\\Users\\Tanganello\\Downloads\\clone1.jpg", FileMode.Create, FileAccess.ReadWrite); 
int accumulator = 0; 
while (accumulator + chuckDim < totalLength) { 
    stream.Read(buffer, accumulator, chuckDim); 
    filestream.Write(buffer, accumulator, chuckDim); 

    accumulator += chuckDim; 
} 
stream.Read(buffer, accumulator, totalLength - accumulator); 
filestream.Write(buffer, accumulator, totalLength - accumulator); 

stream.Close(); 
filestream.Flush(); 
filestream.Close(); 

这是我得到的第一个流: http://img839.imageshack.us/img839/830/clone1h.jpg

回答

4

的问题是,你忽略了Stream.Read Method的返回值:

计数

最大最大字节数d来自当前流。

返回值

读入缓冲区的字节的总数。这可能是不是字节的数量要求


您可以通过简单地使用WebClient.DownloadFile Method避免读写流的整个业务:

using (var client = new WebClient()) 
{ 
    client.DownloadFile(
     "http://media-cdn.tripadvisor.com/media/photo-s/01/70/3e/a9/needed-backup-lol.jpg", 
     "C:\\Users\\Tanganello\\Downloads\\clone1.jpg"); 
} 

或者,如果你真的想要使用流,你可以简单地使用Stream.CopyTo Method

using (var client = new WebClient()) 
using (var stream = client.OpenRead("http://...")) 
using (var file = File.OpenWrite("C:\\...")) 
{ 
    stream.CopyTo(file); 
} 

如果你坚持自己真的复制字节,正确的方式做这将是如下:

using (var client = new WebClient()) 
using (var stream = client.OpenRead("http://...")) 
using (var file = File.OpenWrite("C:\\...")) 
{ 
    var buffer = new byte[512]; 
    int bytesReceived; 
    while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0) 
    { 
     file.Write(buffer, 0, bytesReceived); 
    } 
} 
+0

非常感谢!!!!最后一个正是我所需要的! – Simone