我需要加載一個DLL和依賴項。在我的數據庫中,我已經保存了所有的依賴項(參考文件的路徑)。如何在不同文件夾中加載程序集C#
IE:
DLL加載:
- ID:1
- 名: 「DummyModule.dll」
依賴關係:
- DLL ID: 1
- 路徑: 「C:\ DLL \ ABC.dll」
AssemblyLoader類:
public class AssemblyLoader : MarshalByRefObject
{
public void Load(string path)
{
ValidatePath(path);
Assembly.Load(path);
}
public void LoadFrom(string path)
{
ValidatePath(path);
Assembly.LoadFrom(path);
}
public void LoadBytes(string path)
{
ValidatePath(path);
var b = File.ReadAllBytes(path);
Assembly.Load(b);
}
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.Load(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public Assembly GetAssemblyBytes(string assemblyPath)
{
try
{
var b = File.ReadAllBytes(assemblyPath);
return Assembly.Load(b);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
private void ValidatePath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
if (!File.Exists(path))
throw new ArgumentException(String.Format("path \"{0}\" does not exist", path));
}
}
主類:
static void Main(string[] args)
{
string file1 = @"1\DummyModule.dll";
string file2 = @"2\PSLData.dll";
string file3 = @"3\Security.dll";
try
{
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
var assemblyLoader = (AssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName);
assemblyLoader.LoadBytes(file2);
assemblyLoader.LoadBytes(file3);
var dummy = assemblyLoader.GetAssemblyBytes(file1);
foreach (var t in dummy.GetTypes())
{
var methodInfo = t.GetMethod("D");
if (methodInfo != null)
{
var obj = Activator.CreateInstance(t);
Console.Write(methodInfo.Invoke(obj, new object[] { }).ToString());
}
}
AppDomain.Unload(myDomain);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Console.ReadKey();
}
在上面的代碼的「DummyModule.dll 「是主dll,」PSLData.dll「和」Security.dll「是依賴關係。
當我打電話給我的「DummyModule.dll」錯誤的方式「d」出現:
Could not load file or assembly 'DummyModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
所有DLL文件仍然在不同的文件夾中。我如何加載所有需要的文件並調用函數?
感謝。
大家在做自己的程序集加載預計會通過https://blogs.msdn.microsoft.com/suzcook/tag/loader-info/和https://social.msdn.microsoft.com/search/en完成閱讀-US?rq = site%3Ablogs.msdn.microsoft.com%2Fsuzcook&rn = suzcook&query = fusion +日誌文章...希望最近完成它的人會爲您提供摘要(從長遠來看這真的不會幫助您 - 考慮閱讀文章) –