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

System.OutOfMemoryException when Passing DataSet or DataTable in .Net Remoting

Friday, 22 July 2011 00:06 by ranjanbanerji

Recently noticed that an application was throwing a System.OutOfMemoryException.  A little bit of analysis determined that the exception was being thrown from the application/middle tier which is accessed by the client/web tier via .Net Remoting.  The error was occurring when trying to get a DataSet from the middle tier to the front end via a .Net Remoting interface.  At first I thought the DataSet was huge and using up too much memory.  But on further analysis I noticed that the code for retrieving the data and filling the DataSet worked just fine.  The OutOfMemoryException was occurring somewhere between leaving the remoting host and entering the web code.

That’s when it occurred to me that the problem maybe in the Binary Formatter.  A quick search on the web confirmed my hunch.  The error occurs during the serialization of the DataSet.  To prevent the problem use the RemotingFormat property.  This holds true for a DataTable too.