How to check if file is in use in c#? [duplicate]

巧了我就是萌 提交于 2020-01-14 13:43:10

问题


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#.


回答1:


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?



来源:https://stackoverflow.com/questions/2340607/how-to-check-if-file-is-in-use-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!