AppDomain.CurrentDomain.BaseDirectory
在winform中的OnPaint事件中,AppDomain.CurrentDomain.BaseDirectory得到的是下面这个路径
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE
Application.ExecutablePath得到的是C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.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.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-01-10 sql server 2012中red gate的sql source control消失
2015-01-10 git gc内存错误的解决方案