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

应用程序。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)

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


当前回答

请注意,并非所有这些方法都会返回相同的值。在某些情况下,它们可以返回相同的值,但要注意,它们的目的是不同的:

Application.StartupPath

返回StartupPath参数(可以在运行应用程序时设置)

System.IO.Directory.GetCurrentDirectory()

返回当前目录,该目录可能是应用程序所在的文件夹,也可能不是。Environment.CurrentDirectory也是如此。如果您在DLL文件中使用它,它将返回进程运行的路径(在ASP.NET中尤其如此)。

其他回答

我成功地用过这个

System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

它甚至可以在linqpad内部工作。

这个System.IO.Path.GetDirectory(Application.ExecutablePath)变成了System.IO.Path.GetDirectoryName(Application.ExecutablePath)

根目录:

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

我在会话中通过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

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

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

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

以上代码描述