在Web應用程序中,我想要加載/ bin目錄中的所有程序集。如何從/ bin目錄中加載所有程序集
由於這可以安裝在文件系統的任何位置,因此我無法在它存儲的特定路徑上進行校準。
我想要一個裝配組件對象列表<>。
在Web應用程序中,我想要加載/ bin目錄中的所有程序集。如何從/ bin目錄中加載所有程序集
由於這可以安裝在文件系統的任何位置,因此我無法在它存儲的特定路徑上進行校準。
我想要一個裝配組件對象列表<>。
好了,你可以用下面的方法一起破解這個自己,最初使用類似:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
獲取路徑到您當前裝配。接下來,使用Directory.GetFiles方法通過合適的過濾器遍歷路徑中的所有DLL。你的最終代碼應該是這樣的:
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
foreach (string dll in Directory.GetFiles(path, "*.dll"))
allAssemblies.Add(Assembly.LoadFile(dll));
請注意,我還沒有測試,所以你可能需要檢查的dll實際上包含完整路徑(如果它沒有並置路徑)
你可以這樣做,但你可能不應該像這樣加載到當前的應用程序域,因爲程序集可能包含有害的代碼。編輯:我沒有測試代碼(在這臺計算機沒有訪問Visual Studio),但我希望你明白了。
要獲取bin目錄,string path = Assembly.GetExecutingAssembly().Location;
確實不是不是始終有效(特別是執行程序集已放置在ASP.NET臨時目錄中時)。
相反,你應該使用string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
此外,你應該採取FileLoadException和BadImageFormatException考慮。
這是我的工作職能:
public static void LoadAllBinDirectoryAssemblies()
{
string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin"); // note: don't use CurrentEntryAssembly or anything like that.
foreach (string dll in Directory.GetFiles(binPath, "*.dll", SearchOption.AllDirectories))
{
try
{
Assembly loadedAssembly = Assembly.LoadFile(dll);
}
catch (FileLoadException loadEx)
{ } // The Assembly has already been loaded.
catch (BadImageFormatException imgEx)
{ } // If a BadImageFormatException exception is thrown, the file is not an assembly.
} // foreach dll
}
「bin」目錄不一定會存在於已部署的.NET應用程序中。您應該注意,您的解決方案僅適用於ASP.NET。 – BSick7 2011-06-07 13:56:43
「bin」目錄的位置位於AppDomain.SetupInfomation對象中。用法如下: var assembliesDir = setup.PrivateBinPathProbe!= null ? setup.PrivateBinPath:安裝程序。ApplicationBase; – 2015-10-06 09:27:56
我知道這是一個老問題,但...
System.AppDomain.CurrentDomain.GetAssemblies()
我相信這隻會返回調用程序集引用的程序集(當前程序集依賴的所有程序集)。這並不一定等同於執行目錄中的所有程序集。 http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx – Jason 2012-11-23 23:37:03
你可能也想添加一個檢查以確保你不會添加你實際運行的程序集:) – Wolfwyrd 2009-08-17 15:10:20
'path'變量包含目錄文件名,它需要用'Path.GetDirectoryName(path)'縮短 – cjk 2010-07-29 11:28:50
它是已更新以反映上述評論。 – 2013-05-08 21:41:57