在winform中的OnPaint事件中,AppDomain.CurrentDomain.BaseDirectory得到的是下面这个路径
C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7IDE
Application.ExecutablePath得到的是C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7IDEdevenv.exe
file:///C:/Users/clu/AppData/Local/Microsoft/VisualStudio/15.0_74da2886/ProjectAssemblies/us6sa4js01/Accor.Windows.Forms.dll
https://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-a-net-console-application
System.Reflection.Assembly.GetExecutingAssembly()
.Location
1
Combine that with System.IO.Path.GetDirectoryName
if all you want is the directory.
1As per Mr.Mindor's comment:
System.Reflection.Assembly.GetExecutingAssembly().Location
returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory.System.Reflection.Assembly.GetExecutingAssembly().CodeBase
will return the 'permanent' path of the assembly.
https://stackoverflow.com/a/841320/3782855
AppDomain.CurrentDomain.BaseDirectory
Don't use this. The BaseDirectory can be set at runtime. It is not guaranteed to be correct (like the accepted answer is).
entryAssembly.GetSatelliteAssembly
System.IO.FileNotFoundException: Could not find file 'file:///C:/Users/clu/AppData/Local/Microsoft/VisualStudio/15.0_74da2886/ProjectAssemblies/dgz79z6i01/en-US/Accor.Windows.Forms.resources.DLL'.
File name: 'file:///C:/Users/clu/AppData/Local/Microsoft/VisualStudio/15.0_74da2886/ProjectAssemblies/dgz79z6i01/en-US/Accor.Windows.Forms.resources.DLL'
How do I get the path of the assembly the code is in?
使用codebase是最准的
I've defined the following property as we use this often in unit testing.
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);
}
}
The Assembly.Location
property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use CodeBase
which gives you the path in URI format, then UriBuild.UnescapeDataString
removes the File://
at the beginning, and GetDirectoryName
changes it to the normal windows format.