【收藏】C#中得到程序当前工作目录和执行目录的一些方法

原文:

http://www.cnblogs.com/NalrA/archive/2009/06/15/1503568.html

 

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一样。

以上出处:九头龙的Blog

 

若在类库文件中获取以上各种信息则会产生使用类库的应用程序的目录信息.Highlight的比较常用,下面的是验证测试代码:

 


 1 Process process = Process.GetCurrentProcess();
 2             _fileName = "f://log.txt";
 3             _sw = new StreamWriter(_fileName);
 4             _sw.WriteLine("MainModule is :"+process.MainModule.FileName);
 5             _sw.WriteLine("Environment.CurrentDirectory is :"+Environment.CurrentDirectory);
 6             _sw.WriteLine("System.IO.Directory is :" + System.IO.Directory.GetCurrentDirectory());
 7             _sw.WriteLine("System.AppDomain.CurrentDomain.BaseDirectory is :" + System.AppDomain.CurrentDomain.BaseDirectory);
 8             _sw.WriteLine("System.AppDomain.CurrentDomain.DynamicDirectory is :" + System.AppDomain.CurrentDomain.DynamicDirectory);
 9             _sw.WriteLine("System.AppDomain.CurrentDomain.RelativeSearchPath is :" + System.AppDomain.CurrentDomain.RelativeSearchPath); 
10             _sw.WriteLine("System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase is : " + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
11             _sw.WriteLine("System.Windows.Forms.Application.ExecutablePath is : " + System.Windows.Forms.Application.ExecutablePath);
12             _sw.Flush();
posted @   81  阅读(318)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示