有的时候,当前执行的DLL 和启动的EXE 所在路径并不一致,这时我们想要获得当前执行DLL 所在路径可以使用下面的方法。
// Summary:
// Gets the path or UNC location of the loaded file that contains the manifest.
//
// Returns:
// The location of the loaded file that contains the manifest. If the loaded file
// was shadow-copied, the location is that of the file after being shadow-copied.
// If the assembly is loaded from a byte array, such as when using the System.Reflection.Assembly.Load(System.Byte[])
// method overload, the value returned is an empty string ("").
//
// Exceptions:
// T:System.NotSupportedException:
// The current assembly is a dynamic assembly, represented by an System.Reflection.Emit.AssemblyBuilder
// object.
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// Summary:
// Gets the location of the assembly as specified originally, for example, in an
// System.Reflection.AssemblyName object.
//
// Returns:
// The location of the assembly as specified originally.
public static string AssemblyDirectory { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } }
通过 CodeBase 得到一个 URI 格式的路径;
用 UriBuild.UnescapeDataString 去掉前缀 File://;
用 GetDirectoryName 把它变成正常的 windows 格式。