如何检查文件是否在C#中使用? [英] How to check if file is in use in c#?

查看:82
本文介绍了如何检查文件是否在C#中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查我正在使用的excel文件(操作其数据,删除它或覆盖它)是否被另一个程序使用?如何从相同的版本发布?



请指导我使用C#。

解决方案试图打开与标志写作。如果失败,文件被其他进程占用。

  FileStream fileStream = null; 
$ b $ try
{
fileStream =
FileStream(@c:\file.txt,FileMode.Open,FileAccess.Write);

catch(UnauthorizedAccessException e)
{
//所请求的访问不被操作系统
//允许用于指定的路径,比如访问时是Write或ReadWrite
//并将文件或目录设置为只读访问。
}
finally
{
if(fileStream!= null)
fileStream.Close();
}

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


How can I check if the excel file on which I am working (manipulating its data, deleting it or overwriting it) is in use by another program? And how to release it from the same?

Please guide me using C#.

解决方案

Attempt to open in with flags "for writing". If it fails, the file is "taken" by some other process.

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. Just found a very similar question with basically the same answer:

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

这篇关于如何检查文件是否在C#中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆