加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – FileStream.close()不会为其他进程释放文件

发布时间:2020-12-15 04:05:01 所属栏目:百科 来源:网络整理
导读:我在Page_Load调用函数中有以下代码.在启动Visual Studio后第一次加载页面时,一切正常. 但是在之后对File返回IOException的任何其他开放调用:“文件正由另一个进程使用”,即使在VisualStudio解决方案中直接打开文件时也会返回此错误(当然不是Exception) Fil
我在Page_Load调用函数中有以下代码.在启动Visual Studio后第一次加载页面时,一切正常.
但是在之后对File返回IOException的任何其他开放调用:“文件正由另一个进程使用”,即使在VisualStudio解决方案中直接打开文件时也会返回此错误(当然不是Exception)
FileStream mailinglist_FileStream = new FileStream(@"foobarFile.txt",FileMode.Open);
PeekingStreamReader mailinglist_Reader = new PeekingStreamReader(mailinglist_FileStream);
//Do some stuff with the file
mailinglist_FileStream.Close();
mailinglist_Reader.Close();
mailinglist_Reader.Dispose();
mailinglist_FileStream.Dispose();

为什么文件仍然被锁定?为什么完全重启Visual Studio重置文件?
检查文件属性时它说:

Build Action: Content
Copy to output directory: do not Copy

我只是在读这个文件.我可以做一些类似adLockOptimistic的事情,以便多个进程可以访问文件吗?

解决方法

Why is the file still locked? and why does fully restarting Visual
Studio reset the File? when checking file-Properties it says […]
I don’t know why the file is still locked: probably because your code fails before the stream is closed/disposed.

关于“为什么要完全重新启动Visual Studio […]”:因为您可能正在使用在关闭IDE时关闭的IIS Express或ASP.NET Dev Server,因此锁定文件会被释放,因为持有锁的进程为no运行时间更长

关于“为什么文件仍然被锁定?[…]”可能是因为文件流没有关闭,因为有时线程可能无法成功结束并且锁定没有被释放.

正如其他答案所述,检查使用块如何避免不会丢弃IDisposable对象:

// FileShare.ReadWrite will allow other processes 
// to read and write the target file even if other processes 
// are working with the same file
using (FileStream mailinglist_FileStream = new FileStream(@"foobarFile.txt",FileMode.Open,FileShare.ReadWrite))
using (PeekingStreamReader mailinglist_Reader = new PeekingStreamReader(mailinglist_FileStream))
{
      // Do your stuff. Using blocks will call Dispose() for 
      // you even if something goes wrong,as it's equal to a try/finally! 
      // Also check how using statements can be chained without extra { }           
 }

I am only reading this File. can i do something similiar to
adLockOptimistic,so that multiple processes can access the File?

是的,看一下File.Open方法和FileShare枚举:

> File.Open:http://msdn.microsoft.com/en-us/library/y973b725.aspx
> FileShare枚举:http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读