C#文件例外:因为它正在被其他进程无法访问该文件 [英] C# File Exception: cannot access the file because it is being used by another process

查看:579
本文介绍了C#文件例外:因为它正在被其他进程无法访问该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从网上下载一个文件并将其保存在本地,但我得到一个异常:

I'm trying to download a file from the web and save it locally, but I get an exception:

C#过程因为它正由
其他进程无法访问文件
'胡说'。

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);
}



我已经看到了同样的异常其他许多问题,但他们没有似乎在此适用。任何帮助

I've seen numerous other questions with the same exception, but none of them seem to apply here. Any help?

更新:结果
感谢您的答案!删除 File.Create(...)定了!

的文档上的一个评论 OpenWrite :这是一个有点误导,简要描述说:

One comment on the documentation of OpenWrite: it is a little misleading, the brief description says:

打开一个的 。现有的的文件进行写入

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:结果
检查看起来差异是智能感知/ F1和在线文档之间。我认为这应该是一样的,因为我让F1连接时,它显示文档的网页。

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.

推荐答案

File.Create 返回的FileStream - 这你不关闭。这意味着你将无法打开的其他的流写入到同一个文件,直到终结已关闭现有流。

File.Create returns a FileStream - which you're not closing. That means you won't be able to open another stream writing to the same file until the finalizer has closed the existing stream.

刚刚得到摆脱呼叫到 File.Create - File.OpenWrite 无论如何都会创建它。另外,保持的FileStream 周围写:

Just get rid of the call to File.Create - File.OpenWrite will create it anyway. Alternatively, keep the FileStream around to write to:

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);
    }
}



请注意,我还配置了<$的C $ C> WebResponse类在这里,你应该做的,以确保连接被释放到连接池。

Note that I'm also disposing of the WebResponse here, which you should do to make sure the connection is freed to the connection pool.

这篇关于C#文件例外:因为它正在被其他进程无法访问该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆