I used to work with Webclient and WebClient have file download completed event. But now i'm using this method:
private static void FileDownload(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
Dows the WebRequest , WebResponse or maybe the Stream have something like a completed event ? So if the file downloaded ok i can do stuff ? Like the WebClient file download completed event.
Edit:
I'm trying to use the async way so i did this so far:
HttpWebRequest request;
void FileDownload(string uri, string fileName)
{
request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = false;
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
And then:
void FinishWebRequest(IAsyncResult result)
{
request.EndGetResponse(result);
if (!result.IsCompleted)
{
}
}
The problem is now that at this part: response.ContentType the ContentType is empty "" so it dosen't enter and download the file.
It did before i changed/added the request.BeginGetResponse(new AsyncCallback(FinishWebRequest), null); and the FinishWebRequest.