delete a locked file in csharp

To delete a locked file in c# you need to handle file locking exceptions and force the file to be unlocked before deleting it. You can achieve this by using the File.Open method with FileShare.None like so:

main.cs
try
{
    // Open the file with no sharing
    using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Write, FileShare.None))
    {
        stream.Close();
    }

    // Delete the file now that it's no longer locked
    File.Delete(filePath);
}
catch (IOException ex)
{
    // Handle file locking exception
    Console.WriteLine("File is locked by another process: " + ex.Message);
}
403 chars
17 lines

In the above code, File.Open is used to open the file in FileMode.Open which allows the file to be read and written to. The FileAccess.Write parameter specifies that we want to be able to write to the file, and FileShare.None specifies that no other process should be allowed to share the file while it's open.

If the file is already locked, File.Open will throw an IOException, which we catch and handle by printing a message to the console.

Once the file is successfully opened and closed, we can safely delete it using the File.Delete method.

gistlibby LogSnag