I'm trying to download a file from the web and save it locally, but I get an exception:
C# The process cannot access the file 'blah' because it is being used by another process.
This is my code:
File.Create("data.csv"); // create the file
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
request.Timeout = 30000;
response = (HttpWebResponse)request.GetResponse();
using (Stream file = File.OpenWrite("data.csv"), // <-- Exception here
input = response.GetResponseStream())
{
// Save the file using Jon Skeet's CopyStream method
CopyStream(input, file);
}
I've seen numerous other questions with the same exception, but none of them seem to apply here. Any help?
Update:
Thanks for the answers! Removing the File.Create(...)
fixed it!
One comment on the documentation of OpenWrite
: it is a little misleading, the brief description says:
Opens an existing file for writing.
The detailed description says:
If the file exists, it is opened for writing at the beginning. The existing file is not truncated.
Update 2.0:
It looks like the discrepancy is between IntelliSense/F1 and the online documentation. I thought it should be the same since I allow F1 to connect to the web when it's displaying documentation.