2011-01-21 105 views
47

我有一個配置文件,我需要加載作爲我正在寫的DLL的執行的一部分。如何獲取當前正在執行的DLL的位置?

我遇到的問題是,當應用程序運行時,我放置dll和配置文件的位置不是「當前位置」。

例如,我把這裏的DLL和XML文件:

d:\ Program Files文件\微軟的Team Foundation Server 2010 \應用層\ Web服務\ BIN \插件

但如果我嘗試引用的XML文件(在我的DLL)這樣的:

XDocument doc = XDocument.Load(@".\AggregatorItems.xml") 

然後\ AggregatorItems.xml轉化爲:

C:\ WINDOWS \ SYSTEM32 \ INETSRV \ AggregatorItems.xml

所以,我需要找到知道哪裏是當前正在執行的DLL所在的方式(我希望)。基本上,我在尋找這樣的:

XDocument doc = XDocument.Load([email protected]"\AggregatorItems.xml") 

回答

67

您正在尋找System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml"); 

編輯:

顯然,Location屬性不正確地在某些情況下工作(使用NUnit測試, TFS實例化DLL,Outlook?) - 在這種情況下,您可以使用CodeBase屬性。

+5

唉!返回`C:\\ Windows \\ Microsoft.NET \\ Framework64 \\ v4.0.30319 \\ Temporary ASP.NET Files \\ tfs \\ de3c0c8e \\ c1bdf790 \\ assembly \\ dl3 \\ 20b156cb \\ 22331f24_bfb9cb01 \ \ AggregatorItems.xml` – Vaccano 2011-01-21 23:02:49

+14

啊!但是`Assembly.GetExecutingAssembly()。CodeBase`有它! – Vaccano 2011-01-21 23:05:18

5
System.Reflection.Assembly.GetExecutingAssembly().Location 
24

反思是你的朋友,因爲已經指出。但是你需要使用正確的方法;在Assembly

typeof(OneOfMyTypes).Assembly.CodeBase 

注意使用CodeBase(不Location):

Assembly.GetEntryAssembly()  //gives you the entrypoint assembly for the process. 
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called. 
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined 
Assembly.GetAssembly(Type t) // gives you the assembly in which the specified type is defined. 
12

在我的情況(涉及加載[如文件]到Outlook我的程序集)。其他人已經指出了定位組件的其他方法。

1

如果您使用的是asp.net應用程序,並且想要在使用調試器時找到程序集,則通常會將它們放入臨時目錄中。我寫了這個方法來幫助解決這個問題。

private string[] GetAssembly(string[] assemblyNames) 
{ 
    string [] locations = new string[assemblyNames.Length]; 


    for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)  
    { 
     locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault(); 
    } 
    return locations; 
} 

欲瞭解更多詳情,請參見這篇博客文章http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

如果你不能改變的源代碼,或重新部署,但你可以檢查在計算機使用過程中資源管理器中運行的進程。我寫了詳細的說明here

它會列出系統上所有正在執行的dll,您可能需要確定正在運行的應用程序的進程ID,但通常不會太困難。

我寫的如何IIS裏面的DLL做到這一點充分說明 - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/