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

Comments

January 25. 2014 11:41

pingback

Pingback from camera-site.com

The Importance Of Your Megapixels CCD Sensor Size. | Digital SLR Camea Site

camera-site.com

December 17. 2016 14:30

pingback

Pingback from steroidsforsale.biz

dbol anabolic steroid

steroidsforsale.biz

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading