如何检查文件是否在c#中使用?

如何检查文件是否在c#中使用?,c#,.net,file-io,C#,.net,File Io,如何检查我正在处理的excel文件(操作数据、删除或覆盖数据)是否正在被其他程序使用?如何将其从相同的环境中释放出来 请指导我使用C#。尝试在中打开带有“用于写入”标志的文件。如果失败,该文件将被其他进程“获取” FileStream fileStream = null; try { fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write); } catch (Unautho

如何检查我正在处理的excel文件(操作数据、删除或覆盖数据)是否正在被其他程序使用?如何将其从相同的环境中释放出来


请指导我使用C#。

尝试在中打开带有“用于写入”标志的文件。如果失败,该文件将被其他进程“获取”

FileStream fileStream = null;

try
{
    fileStream =
        new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write);
}
catch (UnauthorizedAccessException e)
{
    // The access requested is not permitted by the operating system
    // for the specified path, such as when access is Write or ReadWrite
    // and the file or directory is set for read-only access. 
}
finally
{
    if (fileStream != null)
        fileStream.Close ();
}
p.S.刚刚发现了一个非常相似的问题,答案基本相同:


你是说捕捉异常?但是,除了通过例外情况进行操作之外,还有其他更干净的方法吗?很好,这对我来说很有效,但我想知道没有其他方法来执行此操作。。。很好,谢谢,但是我在代码中使用了IOException,而不是UnauthorizedAccessException。是的,有例外的话,最好检查一下在不同的场景中抛出的是哪一个。我刚刚阅读了MSDN描述,并选择了一个适合本例的描述。