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.cs403 chars17 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