Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET File locking problem

Tags:

c#

.net

file

I am currently doing the following:

  • I create a file using FileStream braced in the using() tag - Only the file creation takes place within the using statement. The rest of the statements are nearly sequential.
  • Launch the file I have created using Process.Start()
  • Read a small bit of meta data from the file using Assembly.ReflectionOnlyLoadFrom()
  • List the running processes using Process.GetProcessesByName
  • Kill the Process using Process.Kill
  • Try to delete the file using File.Delete()

My problem is that my application is locking the file, so when I try to delete it, nothing happens. It throws an exception saying "Access is Denied" if I try to delete, and throws "Another process is using this file" if I try to write to it.

What on earth could be consuming the file from the above (literally all there is)? I have set all references to null, and gone as far as to call the dreaded GC.Collect() and no luck.

like image 845
Secure The World Avatar asked Jun 25 '26 21:06

Secure The World


1 Answers

When you load assembly it's hosted in the current AppDomain. If you load it using ReflectionOnlyLoad(byte[]) it will load it as shadow and won't lock the file.

var bytes = File.ReadAllBytes(path);
var assembly = Assembly.ReflectionOnlyLoad(bytes);

Currently, the code that blocks the file is Assembly.ReflectionOnlyLoadFrom() and not the writing to the file (assuming the FileStream is disposed before trying to delete). The file will be released only when the AppDomain is unloaded.

like image 67
Elisha Avatar answered Jun 27 '26 10:06

Elisha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!