4

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

Breeze
  • 2,010
  • 2
  • 32
  • 43
Red Swan
  • 15,157
  • 43
  • 156
  • 238

1 Answers1

4

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?

Community
  • 1
  • 1
  • 1
    So you mean by catching exceptions? But any other cleaner way than doing it by exceptions? – pencilCake Feb 26 '10 at 09:44
  • Great it working for me , but wonder there in no other way to perform this... well Thanks But Insted of UnauthorizedAccessException exception I used IOException in my code – Red Swan Feb 26 '10 at 10:05
  • Yes, with exceptions better check out which one is throw in different scenarios. I just read the MSDN description and picked up the one that looked suitable for this example. –  Feb 26 '10 at 10:14