C#获取相对路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27251141/article/details/83055056

C#获取相对路径

1. 程序根目录.(即exe程序所在路径)

//下面两个路径是等价的,都是exe程序所在路径(通常是bin\Debug\下)的Data文件夹下的test文本文件
string Path1 = @".\Data\test.txt"; 
string Path2 = @"Data\test.txt"; 

2. 上级目录…

string Path3 = @"..\Data\test.txt";    //程序根目录的上级目录(通常是bin\下)的Data文件夹下的test文本文件
string Path4 = @"..\..\Data\test.txt";  //程序根目录的上两级目录(通常是程序名\下)的Data文件夹下的test文本文件

下面简要的介绍一下这八种获得相对路径的方式:

1. 获取和设置当前目录(该进程从中启动的目录)的完全限定路径

string str1 = System.Environment.CurrentDirectory; 

2. 获取应用程序的当前工作目录

string str2 = System.IO.Directory.GetCurrentDirectory();

3. 获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称

string str3 = System.Windows.Forms.Application.StartupPath; //Result: C:xxxxxx

4. 获取启动了应用程序的可执行文件的路径,包括可执行文件的名称

string str4 = System.Windows.Forms.Application.ExecutablePath;//Result: C:xxxxxxxxx.EXE

5. 获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集

string str5 = System.AppDomain.CurrentDomain.BaseDirectory;  //Result: C:xxxxxx

6. 获取和设置包含该应用程序的目录的名称

string str6 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//Result: C:xxxxxx

7. 获取当前进程的完整路径,包含文件名

string str7 = this.GetType().Assembly.Location;//Result: C:xxxxxxxxx.exe

8. 获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名

string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//Result: C:xxxxxxxxx.vshost.exe

此外,更多见的通过XML文件配置具体的路径来达到合理的规划配置文件的具体存放位置,如WEB中的配置文件中的路径

string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"moduleM3ExampleMuColor.txt";
StreamReader smRead = new StreamReader(path, System.Text.Encoding.Default);  //设置路径

猜你喜欢

转载自blog.csdn.net/qq_27251141/article/details/83055056