System.UnauthorizedAccessException when Trying to Delete a File

Wednesday, 18 September 2013 00:06 by ranjanbanerji

There are probably several reasons why one would get this error when attempting to delete a file from code:  System.UnauthorizedAccessException: Access to the path ‘blah.exe' is denied.  I recently encountered it when writing a WinForm application and went through the obvious reasons:

  • Permissions.  Does the current user have rights to delete the file in question.
  • Attributes.  Does the file have a read only attribute
  • In use.  Is some other application using, hence, locking the file.

What I did not consider is if the my own code was loading the file.  At first glance the answer was no.  My code was simply looking at the version of an executable and deleting it if it was old.  This was no LoadLibrary kind of code or was it?  After much pondering I decided to look into Assembly.ReflectionOnlyLoadFrom which is how I was loading the executable to get its version.  AssemblyName.GetAssemblyName is the correct way to do so because it does not load the file (thereby does not lock the file).

Version currentVersion = Assembly.ReflectionOnlyLoadFrom( filePath).GetName().Version;  //WRONG WAY as in this will load and keep the assembly in memory
Version currentVersion = AssemblyName.GetAssemblyName( filePath).Version;  //RIGHT WAY as in this will not load the assembly into memory so the file will not be locked.


A day and a half wasted figuring this out.  Awesome!!!!!!!!!!!!!!!