Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check whether File.Delete() will succeed without trying it, in C#?

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().

like image 345
Dylan Beattie Avatar asked Sep 18 '09 12:09

Dylan Beattie


People also ask

How do you delete a file if already exists in C#?

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.

How will you delete an existing file?

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.

How do I delete an existing file and create a new file in C#?

Use File. Delete method to delete a file. Firstly, set the path of the file you want to delete. String myPath = @"C:\New\amit.


2 Answers

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

  • Permissions on the file could change
  • The file could be deleted
  • The file could be locked by another user / process
  • The USB key the file is on could be removed

The best function you could write would most aptly be named FileWasDeletableByCurrentUser.

like image 194
JaredPar Avatar answered Oct 02 '22 15:10

JaredPar


Have you tried System.IO.File.GetAccessControl(filename) it should return a FileSecurity with information about the permissions for that file.

like image 21
Dale Avatar answered Oct 02 '22 13:10

Dale