Hi, How can i check if the excel file on which i a working (manipulating its data or deleting it or overwriting it) is in used ? and how to release it from the same? in c# please guide
+4
A:
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:
Developer Art
2010-02-26 09:41:59
So you mean by catching exceptions? But any other cleaner way than doing it by exceptions?
burak ozdogan
2010-02-26 09:44:27
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
Lalit
2010-02-26 10:05:27
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.
Developer Art
2010-02-26 10:14:08