How to check if a file is locked in C# and VB.NET

To check if a file is locked in C# and VB.NET you can use the following snippet.

Sample C#

public bool IsFileLocked(FileInfo file)
{
	var stream = (FileStream) null;
	try
	{
		stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
	}
	catch (IOException ex)
	{
                //handle the exception your way
		return true;
	}
	finally
	{
		if (stream != null)
		{
			stream.Close();
		}
	}
	return false;
}

Sample VB.NET

Public Function IsFileLocked(file As FileInfo) As Boolean
	Dim stream = DirectCast(Nothing, FileStream)
	Try
		stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
	Catch generatedExceptionName As IOException
                'handle the exception your way
		Return True
	Finally
		If stream IsNot Nothing Then
			stream.Close()
		End If
	End Try
	Return False
End Function

Please Share us:
Please rate this snippet

2 thoughts on “How to check if a file is locked in C# and VB.NET

Leave a Reply