Detecting if a file is already open

  • Thread starter Thread starter CaptainCaveman
  • Start date Start date
C

CaptainCaveman

Hi

Is there a solid method for testing if a file is already open so I dont try
an open a file in use by another process?

TIA
 
I'm assuming from your post that you mean the old classic

try
{
}
catch(exception ex)
{
}
technique?

Is that really the only way?

TIA
 
I'm assuming from your post that you mean the old classic

try
{}

catch(exception ex)
{}

technique?

Is that really the only way?

TIA

public bool FileIsLocked(string strFullFileName) {
bool blnReturn = false;
System.IO.FileStream fs;
try {
fs = System.IO.File.Open(strFullFileName,
IO.FileMode.OpenOrCreate, IO.FileAccess.Read, IO.FileShare.None);
fs.Close();
}
catch (System.IO.IOException ex) {
blnReturn = true;
}
return blnReturn;
}
 
Hi

Is there a solid method for testing if a file is already open so I dont try
an open a file in use by another process?

TIA

the short answer is NO.

You have to try/catch the file operation.
 
I'm assuming from your post that you mean the old classic

try
{}

catch(exception ex)
{}

technique?

Is that really the only way?

YES, there is no other way.
 
I have an app which needs this same thing. Here is the approach I take:

/// <summary>
/// Determines if a specific file is locked
/// </summary>
/// <param name="aFile">File to check for locking</param>
/// <returns>True if inuse; False if available</returns>
public static bool isFileLocked(string aFile)
{
try
{
if ((File.GetAttributes(aFile) & FileAttributes.ReadOnly) !=
FileAttributes.ReadOnly)
{

FileStream fs = new FileStream(aFile, FileMode.Open,
FileAccess.ReadWrite, FileShare.None);
try
{
fs.ReadByte();
}
catch
{
return true;
}
finally
{
fs.Close();
fs.Dispose();
}
}
}
catch
{
return true;
}
return false;
}
 
Ignacio said:
YES, there is no other way.

You can P/Invoke CreateFile which will give an error number instead of
throwing an exception.

Don't forget to CloseHandle on success.
 
Ryan said:
I have an app which needs this same thing. Here is the approach I
take:

I just want to point out that here returning false means "it wasn't locked
when I checked" not "it's unlocked and opening will now succeed". Handling
locking collisions CANNOT reliably be done using a separate isFileLocked
check, it has to be done atomically with opening the file for your own use.
 
CaptainCaveman said:
Hi

Is there a solid method for testing if a file is already open so I
dont try an open a file in use by another process?

TIA

You need to go ahead and try to open the file, any test you can imagine will
return information that is already out-of-date (some program can lock the
file after your test said all is ok and you will still end up trying to open
a locked file).
 
Back
Top