但是在之后对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
解决方法
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