I'm saving an image from a web request and something really weird is happening. On roughly half of the 8,000 images I'm downloading I get IOEXCEPTION errors: ERROR_ACCESS_DENIED (5) INVALID_PARAMETER (87)
Before I save the file using file.open, I check to make sure the file does not exist. The exception is thrown at this line of code:
fileStream = File.Open(destination, FileMode.Create, FileAccess.Write, FileShare.None);
Below is the code:
public static bool DownloadFile(string url, string destination) { bool success = false;
System.Net.HttpWebRequest request = null;
System.Net.WebResponse response = null;
Stream responseStream = null;
FileStream fileStream = null;
try
{
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.Method = "GET";
request.Timeout = 100000; // 100 seconds
request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy();
response = request.GetResponse();
responseStream = response.GetResponseStream();
fileStream = File.Open(destination, FileMode.Create, FileAccess.Write, FileShare.None);
//fileStream = File.Create(destination);
// read up to ten kilobytes at a time
int maxRead = 10240;
byte[] buffer = new byte[maxRead];
int bytesRead = 0;
int totalBytesRead = 0;
// loop until no data is returned
while ((bytesRead = responseStream.Read(buffer, 0, maxRead)) > 0)
{
totalBytesRead += bytesRead;
fileStream.Write(buffer, 0, bytesRead);
}
// we got to this point with no exception. Ok.
success = true;
}
catch (System.Net.WebException we)
{
// something went terribly wrong.
success = false;
//MessageBox.Show(exp.ToString());
writeErrFile(we.ToString(), url);
//Debug.WriteLine(exp);
}
catch (System.IO.IOException ie)
{
// something went terribly wrong.
success = false;
//MessageBox.Show(ie.InnerException.ToString());
writeErrFile(ie.ToString(), destination + " -- " + url);
//Debug.WriteLine(exp);
}
catch (Exception exp)
{
// something went terribly wrong.
success = false;
//MessageBox.Show(exp.ToString());
writeErrFile(exp.ToString(), destination + " -- " + url);
//Debug.WriteLine(exp);
}
finally
{
// cleanup all potentially open streams.
if (null != responseStream)
responseStream.Close();
if (null != response)
response.Close();
if (null != fileStream)
fileStream.Close();
}
// if part of the file was written and the transfer failed, delete the partial file
if (!success && File.Exists(destination))
File.Delete(destination);
return success;
}
I've been stuck on this for a couple of days. Any help would be appreciated in unimaginable orders of magnitude.