Is there a way to check if file is already open?

K

Kimmo Laine

Hi!

Is there a way to check if file is already open/used by another process?

I know that i can do something like this to check it

try {
StreamWriter sw = new StreamWriter(filename);
sw.Close();
} catch (IOException) {
// File is already open...
}

but I would rather use some method then try to open the file in write mode.


thx
Kimmo
 
L

Larry Smith

Hi!
Is there a way to check if file is already open/used by another process?

I know that i can do something like this to check it

try {
StreamWriter sw = new StreamWriter(filename);
sw.Close();
} catch (IOException) {
// File is already open...
}

but I would rather use some method then try to open the file in write
mode.

It's transitory information which you shouldn't normally rely on. A file
that's opened/closed one moment could be closed/opened the next. The safest
route is to simply open the file with the appropriate "FileShare" access.
See this enumeration for details.
 
P

Peter Duniho

Is there a way to check if file is already open/used by another process?

I know that i can do something like this to check it ["try/catch"
snipped]

but I would rather use some method then try to open the file in write
mode.

Why do you want this information?

Note that if you do not yourself open and lock the file, then checking
whether the file is open at any given moment in time is pointless. A
split second after you make the check, the state could change.

If you need to open the file yourself, then just try to open it. If you
don't need to open the file yourself, then there is not usually really any
use in knowing whether the file is already open or used by another process.

(One exception would be if you are trying to write a tool similar to the
Sysinternals FileMon utility, but the kind of things that tool does
requires much lower-level coding than .NET provides).

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top