开发者

.NET File locking problem

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 pr开发者_运维技巧oblem 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.


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.


You can do an analysis with the Process Monitor tool. It can capture the call stack of each file access thus should be sufficient to tell you where/when the file is locked.


Clearly, you are doing something in your code that causes the assembly to be loaded in your own process. Once there, it is stuck and the file is locked until the AppDomain in which it gets loaded gets unloaded. Which is no doubt the primary one, it's stuck until your program terminates.

Pay attention to the Visual Studio Output window, you'll get a debugger notification as soon as it gets loaded. Stepping through your code while watching the windwo will easily isolate the statement that causes it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜