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

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

概述我在Page_Load调用函数中有以下代码.在启动Visual Studio后第一次加载页面时,一切正常. 但是在之后对File返回IOException的任何其他开放调用:“文件正由另一个进程使用”,即使在VisualStudio解决方案中直接打开文件时也会返回此错误(当然不是Exception) FileStream mailinglist_FileStream = new FileStrea 我在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 filemailingList_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 fileusing (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

总结

以上是内存溢出为你收集整理的c# – FileStream.close()不会为其他进程释放文件全部内容,希望文章能够帮你解决c# – FileStream.close()不会为其他进程释放文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1261944.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存