Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Checking to see if a File is Locked
Published: 10/25/2008
XMl / RSS

Many applications (like Word, for example) have a proprietary method for locking their files. This usually involves a temporary file written to the same folder as the file being edited by the application, which typically contains some information like what user is editing the file, how long it's been open, etc. Windows also supports a simple file locking mechanism, which simply generates an error when an application attempts to modify or read from a file that is in use by another application. Here's a simple routine that will check to see if a file is already in use by attempting to open it for read access and trapping the appropriate errors:

VB:
Public Function IsFileLocked(ByVal Path As String) As Boolean 
    Try 
        Using clsReader As New System.IO.StreamReader("C:\MyFile.txt") 
            clsReader.Close() 
        End Using 
        Return False 
    Catch exNotFoundDir As System.IO.DirectoryNotFoundException 
        Throw exNotFoundDir 
    Catch exNotFound As System.IO.FileNotFoundException 
        Throw exNotFound 
    Catch exPathNull As System.ArgumentNullException 
        Throw exPathNull 
    Catch exPath As System.ArgumentException 
        Throw exPath 
    Catch exLocked As System.IO.IOException 
        Return True 
    End Try 
End Function 	
	
C#:
public bool IsFileLocked(string Path)
{
	try
	{
		using (System.IO.StreamReader clsReader = new System.IO.StreamReader("C:\\MyFile.txt"))
		{
			clsReader.Close();
		}
		return false;
	}
	catch (System.IO.DirectoryNotFoundException exNotFoundDir)
	{
		throw exNotFoundDir;
	}
	catch (System.IO.FileNotFoundException exNotFound)
	{
		throw exNotFound;
	}
	catch (System.ArgumentNullException exPathNull)
	{
		throw exPathNull;
	}
	catch (System.ArgumentException exPath)
	{
		throw exPath;
	}
	catch (System.IO.IOException exLocked)
	{
		return true;
	}
}
	



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.