gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:05:19 25 4
gpt4 key购买 nike

我在 Page_Load 函数中有以下代码。启动 Visual Studio 后第一次加载页面时,一切正常。
但是此后对文件的任何其他打开调用都会返回 IOException: "File is in use by another process",即使在 VisualStudio 解决方案中直接打开文件也会返回此错误(当然不是异常)

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 VisualStudio 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 [...]”:因为您可能正在使用 IIS Express 或 ASP.NET Dev Server,它们在您关闭 IDE 时也已关闭,因此锁定文件由于持有锁的进程不再运行而被释放。

关于“为什么文件仍然被锁定?[...]”这可能是因为文件流没有关闭,因为有时线程可能没有成功结束并且锁没有已发布。

正如其他答案所说,检查 using block 如何避免 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 var mailinglist_FileStream = new FileStream(@"\foobarFile.txt", FileMode.Open, FileShare.ReadWrite);
using var 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!

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

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

关于c# - FileStream.close() 不会为其他进程释放文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14955770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com