开发者

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

This question already has answers here: Is there a way to check if a file is in use? (20 answers) 开发者_运维问答 Closed 6 years ago.

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜