Check if file is in use or locked C#

Created by
Monday, June 13, 2016

 

Check if a file is in use before performing some actions on it! Ran into this issue a short while ago and thought i would share how i sovled the problem in C#

 

private void RemoveTemporaryDirectory()
{
	string fileName = Path.GetTempPath();

	string localPath = fileName + @"SOMETHING\";

	// foreach file in path
	DirectoryInfo directory = new DirectoryInfo(localPath);

	foreach (FileInfo fi in directory.GetFiles())
	{
		bool isLocked = LockedFile(fi);

		if (!isLocked)
			fi.Delete();
	}
}

private static bool LockedFile(this FileInfo file)
{
	try
	{
		string filePath = file.FullName;
		FileStream fs = File.OpenWrite(filePath);
		fs.Close();
		return false;
	}
	catch (Exception) { return true; }
}  
Tags:
c#
3
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
2 comments
Monday, June 13, 2016
Nice little trick!! Thanks for sharing.
Wednesday, June 15, 2016
There must be a more efficient way of doing this. What if i were running through a folder with thousands of files? To do a foreach over a collection and follow that up with a try/catch for every item.. that's too intensive..