如何检查文件/exe是否已经打开 [英] how to check if a file/exe is already open
本文介绍了如何检查文件/exe是否已经打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编码员,
如何检查显示"C:\ abc.xls"文件的文件是否已打开,如果是,则如何将其关闭.
问题:我面临的问题是:我的代码崩溃当我尝试编写一个已经打开的文件时,我该如何解决?回答以上问题将成为解决问题的一部分
在此先感谢
Deepak
Hi Coders,
How can I check if a file say "C:\abc.xls" file is already open or not, if yes then how to close it.
Problem: The problem I am facing is: My code crashes When I try to write a file which is already open, how can I solve it? Answer to my question above will be a part of solution to my problem
Thanks in advance
Deepak
推荐答案
您可以使用以下代码检查文件模式:
Hi,
you can check the file mode using the following code:
try
{
//Verify whether the file opens in write mode
using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
if (stream != null)
{
// File is available for write.
break;
}
}
}
catch (FileNotFoundException ex)
{
//The file is not found.
}
catch (IOException ex)
{
//File is undergoing some operation. May be write or copy, etc
}
catch (UnauthorizedAccessException ex)
{
//the User is not authorised to use the file
}
shiva的答案差不多存在.当您尝试打开文件时,使用FileShare.None
.如果文件已经打开,请尝试使用FileShare.None
打开文件,并引发一个异常,您可以对其进行反应.
shiva''s answer is almost there. When you try to open the file, useFileShare.None
. If the file is already open, attempting to open the file withFileShare.None
with throw an exception that you can react to.
您好,
只需添加
Hi,
Just add
using System.IO;
这篇关于如何检查文件/exe是否已经打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文