我是 .NET 用户,我的目标很简单,就是找到主执行程序集(EXE 文件)目录的绝对路径。
我有几个候选人:
Assembly.GetExecutingAssembly().CodeBase
Assembly.GetExecutingAssembly().Location
AppDomain.CurrentDomain.BaseDirectory
如果根据 .NET 文档来判断 - 我倾向于
CodeBase
.谁能用比 .NET 文档更具体的术语来阐明这三个方面?一个例子来证明差异?
最佳答案
我会用 GetEntryAssembly()
而不是 GetExecutingAssembly()
.
要了解原因,请执行以下操作:
ClassLibrary1
) 添加到解决方案并从控制台项目中引用它。 把这个放在
ClassLibrary1
:namespace ClassLibrary1
{
using System;
using System.IO;
using System.Reflection;
public class Class1
{
public void GetInfo(int n)
{
Assembly asm = Assembly.GetEntryAssembly();
Console.WriteLine("[GetEntryAssembly {0}] Location:{1}", n, Path.GetDirectoryName(asm.Location));
asm = Assembly.GetExecutingAssembly();
Console.WriteLine("[GetExecutingAssembly() {0}] Location:{1}", n, Path.GetDirectoryName(asm.Location));
}
}
}
把它放在控制台的
Program.cs
:namespace ConsoleApplication4
{
using System;
using System.IO;
using System.Reflection;
using ClassLibrary1;
class Program
{
static void Main(string[] args)
{
Assembly asm = Assembly.GetEntryAssembly();
Console.WriteLine("[GetEntryAssembly() 1] Location:{0}", Path.GetDirectoryName(asm.Location));
asm = Assembly.GetExecutingAssembly();
Console.WriteLine("[GetExecutingAssembly() 1] Location:{0}", Path.GetDirectoryName(asm.Location));
Class1 obj1 = new Class1();
obj1.GetInfo(2);
asm = Assembly.LoadFile(@"C:\temp\ClassLibrary1.dll");
Type t = asm.GetType("ClassLibrary1.Class1");
object obj2 = asm.CreateInstance("ClassLibrary1.Class1");
t.GetMethod("GetInfo").Invoke(obj2, new object[] { 3 });
Console.ReadKey();
}
}
}
构建解决方案,复制
ClassLibrary1.dll
至 c:\temp
并运行。如您所见,
GetExecutingAssembly()
在某些情况下可能会欺骗您。最后一点,如果您的应用程序是 Windows Forms 应用程序,您可以使用
Application.ExecutablePath
.
关于.net - 使用 Assembly vs AppDomain 查找我的主要可执行文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642827/