wait for webrequest to finish
hi this function downloads an image from source and adds it to a zip file. the problem is sometimes the image comes out all messed up(1/3 is downloaded, the rest is empty space) as if the download isn't finish. how can i make sure the download is finished before i move on? thank you.
edit: i have timeout there so it wouldnt wait indefinitely. should i just extend the timeout? or is there a better way?
public void addImage(string source, string destination)
{
if (isFinalized)
return;
try
{
WebRequest req = WebRequest.Create(source);
req.Timeout = 5000;
WebResponse resp = req.GetResponse();
BufferedStream reader = new BufferedStream(resp.GetResponseStream());
开发者_如何学编程 byte[] fileData = new byte[resp.ContentLength];
reader.Read(fileData, 0, fileData.Length);
zip.AddEntry(destination, fileData);
}
catch (Exception exp)
{
}
}
On your code you need to check the readed bytes and see if you have fully get your image.
int FinalRead = reader.Read(fileData, 0, fileData.Length);
bool fImageIsOk = FinalRead == resp.ContentLength ;
Also I strongly suggest to warp the BufferedStream
with using
I think that the sample code on msdn have a good example.
The part that you must focus is this. Do not try to get at ones your buffer. At the end you can check if you full have get your photo or not. You can also check if the other part is still connected on the process IsClientConnected
int numBytesToRead = receivedData.Length;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = bufStream.Read(receivedData,0, receivedData.Length);
// The end of the file is reached.
if (n == 0)
break;
bytesReceived += n;
numBytesToRead -= n;
}
精彩评论