C#检查文件是否打开 [英] c# check if file is open
问题描述
我需要验证是否打开了特定文件,以防止复制该文件.
I need to verify if specific file is open to prevent the copy of that file.
我尝试了很多例子,但是任何例子都行不通!我尝试例如:
I try lot of examples but any doesn't work! I try, for example, this:
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
我需要方向...我在哪里失败?建议?
I need orientation... where am I fail? suggestions?
推荐答案
您可能会因此而遭受线程竞争的状况,有文献记载将此事用作安全漏洞.如果您检查文件是否可用,然后尝试使用它,那您可能会抛出该文件,恶意用户可能会使用该文件来强制和利用您的代码.
You can suffer from a thread race condition on this which there are documented examples of this being used as a security vulnerability. If you check that the file is available, but then try and use it you could throw at that point, which a malicious user could use to force and exploit in your code.
您最好的选择是try catch/最终尝试获取文件句柄.
Your best bet is a try catch / finally which tries to get the file handle.
try
{
using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
{
// File/Stream manipulating code here
}
} catch {
//check here why it failed and ask user to retry if the file is in use.
}
或
查看其他选项
https://stackoverflow.com/a/11060322/2218635
这篇关于C#检查文件是否打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!