C# 路径的使用

// 摘要:
// 获取或设置包含该应用程序的目录的名称。
//
// 返回结果:
// 应用程序基目录的名称。

AppDomain.CurrentDomain.SetupInformation.ApplicationBase

basePath = AppDomain.CurrentDomain.BaseDirectory;  //得到项目的基目录

Server.MapPath获得的路径都是服务器上的物理路径,也就是常说的绝对路径
1、Server.MapPath("/")
注:获得应用程序根目录所在的位置,如 C:/Inetpub/wwwroot/。
2、Server.MapPath("./")
注:获得所在页面的当前目录,等价于Server.MapPath("")。
3、Server.MapPath("../")
注:获得所在页面的上级目录。
4、Server.MapPath("~/")
注:获得当前应用级程序的目录,如果是根目录,就是根目录,如果是虚拟目录,就是虚拟目录所在的位置,如C:/Inetpub/wwwroot/Example/。

新增加:

AppDomain.CurrentDomain.BaseDirectory在不同项目中路径不同:

在Web Application中直接是项目目录,例如:DBTest项目就是C:/DBTest

在Windows Application中是bin下目录,例如:C:/DBTest/bin/debug

或者C:/DBTest/bin/ 或者C:/DBTest/bin/Release

string str1 =Process.GetCurrentProcess().MainModule.FileName;//可获得当前执行的exe的文件名。 
string str2=Environment.CurrentDirectory;//获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
   //备注 按照定义,如果该进程在本地或网络驱动器的根目录中启动,则此属性的值为驱动器名称后跟一个尾部反斜杠(如“C:/”)。如果该进程在子目录中启   动,则此属性的值为不带尾部反斜杠的驱动器和子目录路径(如“C:/mySubDirectory”)。
string str3=Directory.GetCurrentDirectory();//获取应用程序的当前工作目录。
string str4=AppDomain.CurrentDomain.BaseDirectory;//获取基目录,它由程序集冲突解决程序用来探测程序集。
string str5=Application.StartupPath;//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string str6=Application.ExecutablePath;//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string str7=AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称。

1.      System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
        获取模块的完整路径。
2.      System.Environment.CurrentDirectory
        获取和设置当前目录(该进程从中启动的目录)的完全限定目录。
3.      System.IO.Directory.GetCurrentDirectory() 
        获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:/www里,这个函数有可能返回C:/Documents and Settings/ZYB/,或者C:/Program Files/Adobe/,有时不一定返回什么东东,我也搞不懂了。
4.     System.AppDomain.CurrentDomain.BaseDirectory
        获取程序的基目录。
5.     System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase
        获取和设置包括该应用程序的目录的名称。
6.     System.Windows.Forms.Application.StartupPath 
        获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个"/"而已
7.     System.Windows.Forms.Application.ExecutablePath
        获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。

对于Windows程序和Web 应用程序来说,他们运行的路径是不一样的,所以关键是判断当前运行的程序是哪种程序.于是我们可以使用如下的代码 string path = "";
           if (System.Environment.CurrentDirectory == appDomain.CurrentDomain.BaseDirectory)//Windows应用程序则相等
           {
                 path = AppDomain.CurrentDomain.BaseDirectory;
             }
           else
           {
                 path = AppDomain.CurrentDomain.BaseDirectory + "Bin/";
             }
这样如果我们写了一个类库,类库中用到了Assembly.LoadFrom,由于是通用类库,所以可能用到Windows程序中也可能用到Web中,那么用上面的代码就很方便了.

1、Server.MapPath
2、System.Windows.Forms.StartupPath
3、Type.Assembly.Location

方法2可以应用于控制台应用程序,WinForm应用程序,Windows服务,方法1可以应用于Web应用程序,方法3都可以应用。
但方法3是加载应用程序的路径。如果是Web应用程序,取得的路径是C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary ASP.NET Files目录。所以Web项目还是使用Server.MapPath吧。否则建议使用方法2。如果自己新建类库。可以加入对System.Windows.Forms.StartupPath的引用后使用。

原文地址:https://www.cnblogs.com/kennyliu/p/3639079.html