Excel how to tell if workbook is already open BEFORE you try to openit.

  • Thread starter Thread starter hdjim
  • Start date Start date
H

hdjim

I've been looking all over the net trying to find C# code to determine
if a workbook is open before you try to open it so you can alert the
user to close it before you update it.

There must be a way. Please help.

hd
 
I've been looking all over the net trying to find C# code to determine
if a workbook is open before you try to open it so you can alert the
user to close it before you update it.

There must be a way. Please help.

The easiest way is to try to open the file for writing and see if the
operation fails (i.e., trap the exception).
 
Jeff said:
The easiest way is to try to open the file for writing and see if the
operation fails (i.e., trap the exception).

When you successfully open a file for writing, doesn't that delete the
existing contents?
 
When you successfully open a file for writing, doesn't that delete the
existing contents?

No, depending on the mode you use to open. Think about it: how could you
ever append to a file if that were the case?

I guess you could also try to open for read with a ShareDenyRead lock.
 
Jeff said:
No, depending on the mode you use to open. Think about it: how could you
ever append to a file if that were the case?

OK, fine, for appending. :-) The terminology is tricky--sometimes when
they say "write" they mean, as opposed to "append".
 
OK, fine, for appending. :-) The terminology is tricky--sometimes when
they say "write" they mean, as opposed to "append".

I don't want to harp on it, but it isn't just appending. You can open a file
for "normal" writing and alter the existing contents of a file as well as
adding to the end. Most of the code samples out there for altering the
contents of a file probably read the entire file into memory, alter the
contents, and then write the whole thing back out, but it doesn't HAVE to be
done that way. Probably the best argument against direct manipulation of a
file stream is that if you're reading a file and you discover something you
want to change, you have to back up the stream pointer to overwrite that
particular item. Of course, you have to do this for a MemoryStream too....

For reference, the only members of the FileMode enumeration which will wipe
out an existing file are Create and Truncate.
 
Back
Top