System.Reflection.Assembly.LoadFile Locks File

12,832

If you use this:

 System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(path))

It will not lock the file.

Edit


While this works, it is not the best solution, but the better way of doing it is a lot more involved (too much for just pasting all the code here for it).

I have created a public repository on Github here with all the code for doing this properly:

Loading Assemblies without Locking by using Shadow Copying.

Share:
12,832
Adam Naylor
Author by

Adam Naylor

Everything you need to know about me can be found here: http://www.adamjamesnaylor.com/AboutMe.aspx http://www.adamjamesnaylor.com/contact

Updated on June 06, 2022

Comments

  • Adam Naylor
    Adam Naylor almost 2 years

    I'm loading a DLL via System.Reflection.Assembly.LoadFile and reflecting over it's members in a plugin-esque system. I need to be able to update/overwrite these DLL while the system is running but it appears that after calling System.Reflection.Assembly.LoadFile the file is subsequently locked.
    Does anyone know of a way to unlock the file?
    I have read about loading the file in a separate appdomain? Are there any pitfalls to this approach?

  • Adam Naylor
    Adam Naylor almost 15 years
    That worked perfectly! I'll leave this open just to see if anyone covers some of the other points...
  • dbort
    dbort almost 15 years
    Glad it worked for you :) I have never tried the AppDomain method, although I did read a little about it while looking for a solution to this very problem.
  • jerryjvl
    jerryjvl almost 15 years
    The down-side of this approach would probably be that you cannot 'unload' the assembly from memory, meaning each time you update the DLL and reload you end up with another copy in-memory. The AppDomain method is a bit more circumspect and has a (slight?) performance down-side, but it does mean that you can unload the AppDomain when you no longer need it.
  • Scott
    Scott over 14 years
    This saved me from missing my deadline. Thank you so much!
  • Jan
    Jan about 14 years
    This will work only for standalone libs. If the dll at path has a sub dependency, the assembly loader will be unable to resolve them.
  • dbort
    dbort over 11 years
    @AdamNaylor: I know this is quite an old question/answer, but I have updated it with a link to the proper solution.