我有一个配置文件,我需要加载它作为我正在编写的 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")
然后 .\AggregatorItems.xml 转换为:
C:\windows\system32\inetsrv\AggregatorItems.xml
所以,我需要找到一种方法(我希望)知道当前正在执行的 dll 所在的位置。基本上我在找这个:
XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
最佳答案
您正在寻找System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
注意:
.Location
属性返回当前运行的 DLL 文件的位置。
在某些情况下,DLL 在执行前被影子复制,.Location
属性将返回副本的路径。如果您想要原始 DLL 的路径,请改用 Assembly.GetExecutingAssembly().CodeBase
属性。
.CodeBase
包含一个前缀 (file:\
),您可能需要将其删除。
关于c# - 如何获取当前执行的DLL的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4764680/