C# 文件异常 : cannot access the file because it is being used by another process

标签 c# exception file file-io

我正在尝试从网络上下载文件并将其保存在本地,但出现异常:

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/

相关文章:

c# - Azure 静态网站是否支持使用 https 进行主机名映射

c# - 使用 C# 反序列化带有命名空间的 XML 片段

c# - 使用 DataContractSerializer(typeof(BaseClass)) 反序列化继承类

c# - 尝试将重复对象插入集合时,抛出的正确 .NET 异常是什么?

渲染期间引发的 Android Studio 异常

python tkinter接口(interface)如何创建一个新的显示txt文件

c# - 来源不明的故障转储

c - 如何在预构建中编译自动生成的 C 文件?

java - 有没有办法在 Linux 上用 Java 原子地写入文件?

Java,1 个 try block ,2 个不同的构造函数抛出相同的异常,分开?