How to get the location of the DLL currently executing?
I have a config file that I need to load as part of the execution of a dll I am writing.
The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.
For example, I put the dll and xml file here:
D:Program FilesMicrosoft Team Foundation Server 2010Application TierWeb ServicesbinPlugins
But if I try to reference the xml file (in my dll) like this:
XDocument doc = XDocument.Load(@".AggregatorItems.xml")
then .AggregatorItems.xml translates to:
C:windowssystem32inetsrvAggregatorItems.xml
So, I need to find a way (I hope) of knowing where the dll that is currently executing is located. Basically I am looking for this:
XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"AggregatorItems.xml")
You are looking for System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Edit:
Apparently the Location
property does not work correctly under some conditions (testing using NUnit, TFS instantiated DLL, Outlook?) - in that case you can use the CodeBase
property.
Reflection is your friend, as has been pointed out. But you need to use the correct method;
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.
In my case (dealing with my assemblies loaded [as file] into Outlook):
typeof(OneOfMyTypes).Assembly.CodeBase
Note the use of CodeBase
(not Location
) on the Assembly
. Others have pointed out alternative methods of locating the assembly.
上一篇: 最佳方式来帮助Windows找到我链接到的DLL?
下一篇: 如何获取当前正在执行的DLL的位置?