Here is a simple code to check if a file is locked if it exists. If the file does not exist, it checks whether the file can be created
public static bool IsFileLocked(FileInfo file)
{
try
{
using FileStream stream = file.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
stream.Close();
}
catch (IOException)
{
return true;
}
return false;
}
It also very useful to know what process is locking the file, so here is another piece of code that is able to get this process name: https://stackoverflow.com/a/20623302/987949
Tags
windows