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

时间:2010-02-26 09:36:02

标签: c# .net file-io

如何检查我正在使用的excel文件(操作其数据,删除或覆盖它)是否正被另一个程序使用?以及如何从中释放它?

请指导我使用C#。

1 个答案:

答案 0 :(得分:4)

尝试用“写作”标志打开。如果失败,该文件将由其他进程“处理”。

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。刚刚找到一个非常相似的问题,答案基本相同:

C#: Is there a way to check if a file is in use?