如何在C#中检查文件是否正在被使用?

16 浏览
0 Comments

如何在C#中检查文件是否正在被使用?

这个问题在这里已经有答案:

有没有办法检查文件是否正在使用中?

我如何检查正在使用的另一个程序是否正在使用我正在处理的Excel文件(操纵其数据,删除它或覆盖它)? 怎么去释放它呢?

请用C#指导我。

admin 更改状态以发布 2023年5月22日
0
0 Comments

尝试以“写入”标志打开文件。如果失败,文件就被其他进程“占用”了。

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 ();
}

附注:刚刚发现一个非常类似的问题,基本上是相同的答案:

C#: 是否有一种方法可以检查文件是否正在使用中?

0