Vac*_*ano 78 .net c# dll file-io
我有一个配置文件,我需要加载作为我正在编写的DLL的执行的一部分.
我遇到的问题是,当应用程序运行时,我放置dll和配置文件的位置不是"当前位置".
例如,我把dll和xml文件放在这里:
D:\ Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins
但是,如果我尝试像这样引用xml文件(在我的dll中):
XDocument doc = XDocument.Load(@".\AggregatorItems.xml")
Run Code Online (Sandbox Code Playgroud)
然后.\ AggregatorItems.xml转换为:
C:\ WINDOWS\SYSTEM32\INETSRV\AggregatorItems.xml
所以,我需要找到一种方法(我希望)知道当前正在执行的dll所在的位置.基本上我正在寻找这个:
XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
Run Code Online (Sandbox Code Playgroud)
Bro*_*ass 118
你在找 System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Run Code Online (Sandbox Code Playgroud)
注意:
该.Location属性返回当前运行的DLL文件的位置.
在某些情况下,DLL在执行之前被复制阴影,.Location属性将返回副本的路径.如果需要原始DLL的路径,请改用该Assembly.GetExecutingAssembly().CodeBase属性.
.CodeBase包含一个前缀(file:\),您可能需要删除它.
Nic*_*rey 33
正如已经指出的那样,反思是你的朋友.但是你需要使用正确的方法;
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.
Run Code Online (Sandbox Code Playgroud)
小智 14
在我的情况下(处理我的程序集[作为文件]加载到Outlook中):
typeof(OneOfMyTypes).Assembly.CodeBase
Run Code Online (Sandbox Code Playgroud)
注意使用CodeBase(不Location)的Assembly.其他人已经指出了定位组件的替代方法.