In C#, System.IO.File.Delete(filePath) will either delete the specified file, or raise an exception. If the current user doesn't have permission to delete the file, it'll raise an UnauthorizedAccessException.
Is there some way that I can tell ahead of time whether the delete is likely to throw an UnauthorizedAccessException or not (i.e. query the ACL to see whether the current thread's identity has permission to delete the specified file?)
I'm basically looking to do:
if (FileIsDeletableByCurrentUser(filePath)) { /* remove supporting database records, etc. here */ File.Delete(filePath); }
but I have no idea how to implement FileIsDeletableByCurrentUser().
Delete(path) method is used to delete a file in C#. The File. Delete() method takes the full path (absolute path including the file name) of the file to be deleted. If file does not exist, no exception is thrown.
Locate the file that you want to delete. Right-click the file, then click Delete on the shortcut menu. Tip: You can also select more than one file to be deleted at the same time. Press and hold the CTRL key as you select multiple files to delete.
Use File. Delete method to delete a file. Firstly, set the path of the file you want to delete. String myPath = @"C:\New\amit.
The problem with implementing FileIsDeletableByCurrentUser
is that it's not possible to do so. The reason is the file system is a constantly changing item.
In between any check you make to the file system and the next operation any number of events can and will happen. Including ...
The best function you could write would most aptly be named FileWasDeletableByCurrentUser
.
Have you tried System.IO.File.GetAccessControl(filename) it should return a FileSecurity with information about the permissions for that file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With