By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,143 Members | 1,645 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,143 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
May 31 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.
May 31 '07 #2

P: n/a
On Thu, 31 May 2007 07:30:12 -0700, Kimmo Laine <re******@newsgroup.only>
wrote:
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
May 31 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.