C# 相对路径

一.C# winform 

1.image 

 pictureBox1.Image = Image.FromFile(Application.StartupPath + @"1.jpg");

 Application.StartupPath  一般为Debug文件夹下的进行查找

 pictureBox1.Image = Image.FromFile(string path);

string Parth=AppDomain.CurrentDomain.BaseDirectory+@"Photoempty.png";

AppDomain.CurrentDomain.BaseDirectory 程序运行目录

(转载)

1、 根目录

.// 或者直接给出文件名称,是找根目录的路径。

如:path = "test.xml" 与 path = ".//test.xml"是一个意思。

2、 根目录的上级目录, 在C#中是指定到bin文件夹里面

..// 应用程序的根目录的上两级

3、指定到根目录上面的三级目录,也就是C#中与bin同一目录中

..//..//test.xml 这个意思是在根目录的三级目录的gs.mdb文件

如果在这级目录中你要指定到指定文件夹中的某个文件,应该这样: ..//..//xml//test.xml意思在这个目录中的xml文件下面的test.xml文件。

4、指定到根目录的上四级目录,如下:

..//..//..// 这样就指定到根目录的第四级目录了。

..//..//..//xml//test.xml 这样就指定到这个目录里面的dir这个文件夹里面的gs.mdb这个路径。

5、某个文件的相对路径

..//Draw//xml//test.xml这种情况如:例如现在有几个文件夹xml 、 Draw、 tool,而应用程序现在在xml文件夹里面,那么这个路径的意思是指定在xml文件的上两级目录的Draw的bin中的test.xml的文件路径。

原文:http://blog.sina.com.cn/s/blog_449f737a0100hj07.html

1.获取和设置当前目录的完全限定路径。

string str = System.Environment.CurrentDirectory;

Result: C:/xxx/xxx

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

string str = System. Windows .Forms.Application.StartupPath;

Result: C:/xxx/xxx

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

string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

Result: C:/xxx/xxx/xxx.exe

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

string str = System.AppDomain.CurrentDomain.BaseDirectory;

Result: C:/xxx/xxx/

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

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

Result: C:/xxx/xxx

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

string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

Result: C:/xxx/xxx/

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

string str = this.GetType().Assembly.Location;

Result: C:/xxx/xxx/xxx.exe

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

string str = System. Windows .Forms.Application.ExecutablePath;

Result: C:/xxx/xxx/xxx.exe

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


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;//获取或设置包含该应用程序的目录的名称。

原文地址:https://www.cnblogs.com/hanke123/p/5940595.html