我看到有一些方法来获得应用程序文件夹路径:

应用程序。StartupPath System.IO.Path.GetDirectoryName ( System.Reflection.Assembly.GetExecutingAssembly () .Location) AppDomain.CurrentDomain.BaseDirectory System.IO.Directory.GetCurrentDirectory () 环境。CurrentDirectory System.IO.Path.GetDirectoryName ( System.Reflection.Assembly.GetExecutingAssembly () . getname () .CodeBase) System.IO.Path.GetDirectory (Application.ExecutablePath)

根据具体情况,最好的方法是什么?


当前回答

AppDomain.CurrentDomain.BaseDirectory可能是访问位置相对于应用程序安装目录的文件最有用的目录。

在ASP中。NET应用程序,这将是应用程序的根目录,而不是bin子文件夹-这可能是您通常想要的。在客户端应用程序中,它将是包含主要可执行文件的目录。

在VSTO 2005应用程序中,它将是包含应用程序的VSTO托管程序集的目录,而不是Excel可执行文件的路径。

其他选项可能会根据您的环境返回不同的目录—例如,请参阅@Vimvq1987的答案。

CodeBase是找到文件的地方,可以是以http://.开头的URL在这种情况下,Location可能是程序集下载缓存。CodeBase不保证为GAC中的程序集设置。

更新 这些天….NET Core, .NET Standard 1.3+或.NET Framework 4.6+),最好使用AppContext。而不是AppDomain.CurrentDomain.BaseDirectory。两者是等效的,但不再支持多个appdomain。

其他回答

根目录:

DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;

Application.StartupPathand 7. System.IO.Path.GetDirectoryName(Application.ExecutablePath) - Is only going to work for Windows Forms application System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location) Is going to give you something like: "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\legal-services\\e84f415e\\96c98009\\assembly\\dl3\\42aaba80\\bcf9fd83_4b63d101" which is where the page that you are running is. AppDomain.CurrentDomain.BaseDirectory for web application could be useful and will return something like "C:\\hg\\Services\\Services\\Services.Website\\" which is base directory and is quite useful. System.IO.Directory.GetCurrentDirectory() and 5. Environment.CurrentDirectory

将为您提供进程从哪里启动的位置-因此,对于运行在Visual Studio调试模式下的web应用程序,例如“C:\\Program Files (x86)\\IIS Express”

System.IO.Path.GetDirectoryName ( System.Reflection.Assembly.GetExecutingAssembly () . getname () .CodeBase)

将为您提供运行代码的.dll的位置,对于web应用程序,可以是“file:\\C:\\hg\\Services\\Services\\Services”。网站\ \ bin "

现在,例如控制台应用程序点2-6将是。exe文件所在的目录。

希望这能为您节省一些时间。

我在会话中通过Win32 API从Windows服务启动了一个进程,从实际登录的用户(在任务管理器会话1而不是0中)。在这是我们可以知道,哪个变量是最好的。

对于上述问题中的所有7个案例,结果如下:

Path1: C:\Program Files (x86)\MyProgram
Path2: C:\Program Files (x86)\MyProgram
Path3: C:\Program Files (x86)\MyProgram\
Path4: C:\Windows\system32
Path5: C:\Windows\system32
Path6: file:\C:\Program Files (x86)\MyProgram
Path7: C:\Program Files (x86)\MyProgram

也许这对你们中的一些人是有帮助的,当你为你的情况寻找最佳变量时。

如果你知道根目录:

string rootPath = Path.GetPathRoot(Application.StartupPath)

对于web应用程序,要获得当前web应用程序根目录,通常通过web页面调用当前传入的请求:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

以上代码描述