这是我如何做到这一点的时刻。我尝试打开与文件共享设置为无文件。所以我想独占accesss到文件中。如果我不能拿到那么它的一个不错的选择别人已经锁定该文件。
我们有了一个更好的,更快的方式。任何想法?
尝试
{
使用(的FileStream FS = File.open方法(GetLockFilename(),FileMode.Open,FileAccess.ReadWrite,FileShare.None))
{
fs.Close();
}
//该文件没有锁定
}
赶上(例外)
{
//该文件被锁定
}
解决方案
无需首先检查文件是否被锁定,然后访问它,检查和接入之间的一些其他进程可能仍然获得了锁文件。所以,你做的是正确的,如果你成功了,对文件做你的工作。
This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.
There's got to be a better and faster way. Any ideas?
try
{
using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fs.Close();
}
// The file is not locked
}
catch (Exception)
{
// The file is locked
}
解决方案
There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.
上一篇:正确使用GC.Collect的(); GC.WaitForPendingFinalizers();?正确、GC、WaitForPendingFinalizers、Collect
下一篇:ASP.net应用程序崩溃 - 无法加载文件或程序集“Microsoft.Threading.Tasks.Extensions.Desktop”应用程序、加载、文件、程序