如何检查文件/exe是否已经打开

如何检查文件/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, use FileShare.None. If the file is already open, attempting to open the file with FileShare.None with throw an exception that you can react to.


您好,

只需添加

Hi,

Just add

using System.IO;