Find File is locked

Is there a way to check if a file is in use/locked by another process ?

File Open Mode

Checking with FileAccess.ReadWrite will fail for Read-Only files so the solution has been modified to check with FileAccess.Read. While this solution works because trying to check with FileAccess.Read will fail if the file has a Write or Read lock on it, however, this solution will not work if the file doesn't have a Write or Read lock on it, i.e. it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access.

Example method: To find the file is read only or not ?

/// <summary>
/// Fild if the file is opened or not.
/// </summary>
/// <example>
/// <code>
/// FileInfo fileInfo = new FileInfo(@"\\10.187.139.233\c$\SharePath\TestFolder\New.docx");
/// </code>
/// </example>
/// <param name="file"></param>
/// <returns></returns>
protected virtual bool IsFileLocked(FileInfo file)
{
	bool isFileLocked = false;
	try
	{
		using (FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
		{
			stream.Close();
		}
	}
	catch (IOException ex)
	{
		//the file is unavailable because it is:
		//still being written to
		//or being processed by another thread
		//or does not exist (has already been processed)
		isFileLocked =  true;
	}
	//file is not locked
	return isFileLocked;
}

This method can be used to do find before move/delete the file, which act as a safe delete.

How to use this method ?

FileInfo fileInfo = new FileInfo(@"\\10.187.139.233\c$\SharePath\TestFolder\New.docx");
IsFileLocked(fileInfo);

Last updated

Was this helpful?