Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c# - Assembly loaded using Assembly.LoadFrom() on remote machine causes SecurityException

I am loading an assembly using Assembly.LoadFrom(fileName). When fileName is on the local machine, everything works fine. When, however, the identical file (and dependencies) are on a remote network share, I get a System.Security.SecurityException the moment I try to create a new SqlConnection from the remote assembly:

System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

What's the cure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could load the assembly as bytes and load it with Assembly.Load(bytes), maybe this works.

Or you give the application the requested permission.

Edit:

I made a little test and it worked for me. Here is some code:

static Dictionary<Assembly, String> _Paths = new Dictionary<Assembly, String>();

static void Main(string[] args)
{
    AppDomain current = AppDomain.CurrentDomain;
    current.AssemblyResolve += new ResolveEventHandler(HandleAssemblyResolve);

    // This line loads a assembly and retrieves all types of it. Only when
    // calling "GetTypes" the 'AssemblyResolve'-event occurs and loads the dependency
    Type[] types = LoadAssembly("Assemblies\MyDLL.dll").GetTypes();
    // The next line is used to test permissions, i tested the IO-Permissions 
    // and the Reflection permissions ( which should be denied when using remote assemblies )
    // Also this test includes the creation of a Form
    Object instance = Activator.CreateInstance(types[0]);
}

private static Assembly LoadAssembly(string file)
{
    // Load the assembly
    Assembly result = Assembly.Load(File.ReadAllBytes(file));
    // Add the path of the assembly to the dictionary
    _Paths.Add(result, Path.GetDirectoryName(file));
    return result;
}

static Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args)
{
    // Extract file name from the full-quallified name
    String name = args.Name;
    name = name.Substring(0, name.IndexOf(','));
    // Load the assembly
    return LoadAssembly(Path.Combine(_Paths[args.RequestingAssembly], name + ".dll"));
}

Something important:

There may be files which do not have a matching name and file name, but you can resolve this by checking all files in folder with AssemblyName.GetAssemblyName(file).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...