最後我做到了幾乎完全raboof的方式提出(以及類似dgvid建議是什麼),但有一些小的變化和一些遺漏固定。我選擇了這個方法,因爲它是最接近於我一直在尋找在首位的,不需要使用任何第三方可執行文件和這樣的。它很棒!
這是我的代碼結束什麼看起來像:
編輯:我決定把這個功能移動到另一個程序集,所以我可以在多個文件中重複使用它(我只是傳遞Assembly.GetExecutingAssembly())。
這是更新的版本,它允許您在裝配通過與嵌入式dll文件。
embeddedResourcePrefix是嵌入式資源的字符串路徑,它通常是程序集的名稱,後跟包含資源的任何文件夾結構(例如,「MyComapny.MyProduct.MyAssembly.Resources」,如果dll位於名爲項目中的資源)。它還假定該dll具有.dll.resource擴展名。
public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { // had to add =>
try {
string resName = embeddedResourcePrefix + "." + args.Name.Split(',')[0] + ".dll.resource";
using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
} catch (Exception ex) {
_log.Error("Error dynamically loading dll: " + args.Name, ex);
return null;
}
}; // Had to add colon
}
private static byte[] StreamToBytes(Stream input) {
int capacity = input.CanSeek ? (int)input.Length : 0;
using (MemoryStream output = new MemoryStream(capacity)) {
int readLength;
byte[] buffer = new byte[4096];
do {
readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
發佈後發現@dgvid在響應時間內擊敗了我。 :P – 2008-09-18 21:44:05
我非常成功地使用此代碼來完成我想要的功能。查看我的帖子,瞭解我修復的一些次要語法遺漏(沒有足夠的代表編輯這個;))。 – 2008-09-19 17:14:48