我正在尝试从网络上下载文件并将其保存在本地,但出现异常:
C# The process cannot access the file 'blah' because it is being used by another process.
这是我的代码:
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);
}
我已经看到许多其他问题都有相同的异常(exception),但似乎没有一个适用于此。有帮助吗?
更新:
感谢您的回答!删除 File.Create(...)
修复它!
关于OpenWrite
文档的评论:有点误导,简要说明说:
Opens an existing file for writing.
详细描述说:
If the file exists, it is opened for writing at the beginning. The existing file is not truncated.
2.0 更新:
看起来 IntelliSense/F1 和联机文档之间存在差异。我认为它应该是一样的,因为我允许 F1 在显示文档时连接到网络。
最佳答案
File.Create
返回一个 FileStream
- 您没有关闭它。这意味着在终结器关闭现有流之前,您将无法打开写入同一文件的另一个流。
只是摆脱对 File.Create
的调用 - File.OpenWrite
无论如何都会创建它。或者,保持 FileStream
写入:
using (Stream file = File.Create("data.csv"))
{
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
request.Timeout = 30000;
using (var response = (HttpWebResponse)request.GetResponse())
using (Stream input = response.GetResponseStream())
{
// Save the file using Jon Skeet's CopyStream method
CopyStream(input, file);
}
}
请注意,我还在这里处理了 WebResponse
,您应该这样做以确保连接已释放到连接池。
关于C# 文件异常 : cannot access the file because it is being used by another process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2701685/