我会使用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 窗体应用程序,您可以只使用Application.ExecutablePath
.