I want to check whether a particular Excel file is already opened. Otherwise when I reopen same file in my C# program it is opening in read only format. Is there any way to find out if the file is already open?
Asked
Active
Viewed 8,795 times
0
-
If you want to open the file for reading purposes only, make a copy of the file prior to opening it, that will solve the "read only" problem – Shai Jul 11 '12 at 07:07
-
possible duplicate of [Is there a way to check if a file is in use?](http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use) – Shai Jul 11 '12 at 07:08
-
@shai No,i wanted to close tht file if it is already open then,need to create new sheet and write data. – Film Creator Jul 11 '12 at 07:28
1 Answers
0
If the file if opened by another program this code can help you figure it out, but you won't be able to open it
<!-- language: c# -->
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
(BUt you can't do anything with it, the file must be closed from the program, which opened it)

amman
- 142
- 4
- 12
-
6Why just copy the code without pointing to the [original answer](http://stackoverflow.com/a/937558/362938)? – detunized Jul 11 '12 at 11:03