C#如何获取当前路径的父路径

时间:2023-10-07 09:29:50来源:互联网

下面小编就为大家分享一篇C#如何获取当前路径的父路径,具有很好的参考价值,希望对大家有所帮助。

C#如何获取当前路径的父路径C#获取当前路径7种方法代码用法须知总结

C#如何获取当前路径的父路径

//获取当前运行路径的上级目录(父目录)

 System.IO.DirectoryInfo topDir = System.IO.Directory.GetParent(System.Environment.CurrentDirectory);//D:项目测试testbinDebug

//继续获取上级的上级的上级的目录。

string pathto = topDir.Parent.Parent.FullName;//D:项目测试test

获取路径中最后一个文件夹的名字

string fileName = Path.GetFileNameWithoutExtension("E:dyl190909DemoCulculateTestCulculateView.cs");//fileName结果为Culculate

注:一个Parent获取向上一级的目录。

C#获取当前路径7种方法

代码

//获取模块的完整路径。string path1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取和设置当前目录(该进程从中启动的目录)的完全限定目录string path2 = System.Environment.CurrentDirectory;//获取应用程序的当前工作目录string path3 = System.IO.Directory.GetCurrentDirectory();//获取程序的基目录string path4 = System.AppDomain.CurrentDomain.BaseDirectory;//获取和设置包括该应用程序的目录的名称string path5 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取启动了应用程序的可执行文件的路径string path6 = System.Windows.Forms.Application.StartupPath;//获取启动了应用程序的可执行文件的路径及文件名string path7 = System.Windows.Forms.Application.ExecutablePath;StringBuilder str=new StringBuilder();str.AppendLine("System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:" + path1);str.AppendLine("System.Environment.CurrentDirectory:" + path2);str.AppendLine("System.IO.Directory.GetCurrentDirectory():" + path3);str.AppendLine("System.AppDomain.CurrentDomain.BaseDirectory:" + path4);str.AppendLine("System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:" + path5);str.AppendLine("System.Windows.Forms.Application.StartupPath:" + path6);str.AppendLine("System.Windows.Forms.Application.ExecutablePath:" + path7);string allPath = str.ToString();

输出结果

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:D:workprjVP-VPlatformXmlAndXsdbinReleaseXmlAndXsd.vshost.exe
System.Environment.CurrentDirectory:D:workprjVP-VPlatformXmlAndXsdbinRelease
System.IO.Directory.GetCurrentDirectory():D:workprjVP-VPlatformXmlAndXsdbinRelease
System.AppDomain.CurrentDomain.BaseDirectory:D:workprjVP-VPlatformXmlAndXsdbinRelease
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:D:workprjVP-VPlatformXmlAndXsdbinRelease
System.Windows.Forms.Application.StartupPath:D:workprjVP-VPlatformXmlAndXsdbinRelease
System.Windows.Forms.Application.ExecutablePath:D:workprjVP-VPlatformXmlAndXsdbinReleaseXmlAndXsd.EXE

用法须知

1、Net Framework中System.IO.Directory.GetCurrentDirectory()方法用于获得应用程序当前工作目录。

如果使用此方法获得应用程序所在的目录,应该注意:System.IO.Directory.GetCurrentDirectory()方法获得的目录路径随着OpenFileDialog、SaveFileDialog等对象所确定的目录而改变(切换工作目录)。

每打开一次文件夹或者使用资源管理器查看一下文件,都会更改此方法获得的值。

2、而System.Windows.Forms.Application.StartupPath或System.AppDomain.CurrentDomain.BaseDirectory可以获得应用程序运行所在的目录,它是不随你打开的文件夹而变的。

只跟应用程序运行目录有关,其值等于应用程序启动的根目录。

例如你安装了程序在了C:Program Files程序文件夹 的位置下,那么他就是System.Windows.Forms.Application.StartupPath的值。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持阿里西西。

本站部分内容转载自互联网,如果有网站内容侵犯了您的权益,可直接联系我们删除,感谢支持!