C# 加载网络映射盘中的assembly失败

来源:互联网 发布:林志玲人品如何 知乎 编辑:程序博客网 时间:2024/04/30 00:46

我有一个网络映射盘,盘符是Z:。在Z盘下面,放了一个assembly,名为test.dll。然后,我在VS2010中建立了一个.NET 4.0的工程,程序中有下面一段代码:

[html] view plaincopy
  1. string dll = @"Z:\test.dll";  
  2. Assembly a = Assembly.LoadFrom(dll);  
执行代码,抛出FileLoadException异常:Could not load file or assembly 'file:///Y:\bb\nvo_cas.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)。

深入到内部异常:An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.。

看来是.NET的安全机制阻止加载一个网络上(本地网或者互联网)的assembly。

【办法一】

根据提示,找到了MSDN的一篇文章。文章给出的解决办法是:在程序的配置文件中加入下面的xml片段:

[html] view plaincopy
  1. <configuration>  
  2.   ......  
  3.   <runtime>  
  4.     <!-- WARNING: will load assemblies from remote locations as fully trusted! -->  
  5.     <loadFromRemoteSources enabled="true" />  
  6.   </runtime>  
  7.   ......  
  8. </configuration>  

按照这个解决办法,程序运行正确。

MSDN链接:http://msdn.microsoft.com/en-us/library/dd409252(VS.100).aspx。

【办法二】

Assembly类有一个静态函数UnsafeLoadFrom,这个函数在加载一个assembly的时候,不会进行一些安全检查。将原先的代码修改如下即可:

[html] view plaincopy
  1. string dll = @"Z:\test.dll";  
  2. Assembly a = Assembly.UnsafeLoadFrom(dll);  

【办法三】

Assembly的load方法有很多的重载,可以使用其中的一个参数为byte[]的load函数。代码如下:

[html] view plaincopy
  1. string dll = @"Z:\test.dll"; ;  
  2. byte[] assemblyBuffer = File.ReadAllBytes(dll);  
  3. Assembly a = Assembly.Load(assemblyBuffer);