Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - 有没有办法检查文件是否正在使用?(Is there a way to check if a file is in use?)

I'm writing a program in C# that needs to repeatedly access 1 image file.

(我正在用C#编写一个程序,该程序需要重复访问1个图像文件。)

Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error: "File in use by another process" .

(在大多数情况下,它都可以工作,但是如果我的计算机运行速度很快,它将在尝试将文件保存回文件系统之前尝试访问该文件,并抛出错误: “文件正在被另一个进程使用” 。)

I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling.

(我想找到一种解决方法,但是我所有的Google搜索都只能通过使用异常处理来创建检查。)

This is against my religion, so I was wondering if anyone has a better way of doing it?

(这与我的宗教信仰背道而驰,所以我想知道是否有人能做得更好?)

  ask by Dawsy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(如果您检查该文件是否可用,然后尝试使用它,则可能会丢掉该文件,恶意用户可能会使用该文件来强制和利用您的代码。)

Your best bet is a try catch / finally which tries to get the file handle.

(最好的选择是try catch /最终尝试获取文件句柄。)

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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...