C#获取当前程序运行路径的几种方法

发布时间 2023-04-06 15:03:47作者: bxzjzg

从外部程序启动另一个程序,路径有点不一样;

 logger.InfoFormat($"{System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName},
{System.Environment.CurrentDirectory},{System.IO.Directory.GetCurrentDirectory()}" +
                    $",{System.AppDomain.CurrentDomain.BaseDirectory}" +
                        $",{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase},
{System.Windows.Forms.Application.StartupPath},{System.Windows.Forms.Application.ExecutablePath}");

从StartProject程序启动Operator程序获取的路径:

D:\project\yitiji\test\Bin\Operator.exe,
D:\project\yitiji\启动程序\StartProject\bin\Debug,
D:\project\yitiji\启动程序\StartProject\bin\Debug,
D:\project\yitiji\test\Bin\,
D:\project\yitiji\test\Bin\,
D:\project\yitiji\test\Bin,
D:\project\yitiji\test\Bin\Operator.exe
View Code

 

1. 获取模块的完整路径。
string path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.vshost.exe
2. 获取和设置当前目录(该进程从中启动的目录)的完全限定目录
string path = System.Environment.CurrentDirectory;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
3. 获取应用程序的当前工作目录
string path = System.IO.Directory.GetCurrentDirectory();
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
4. 获取程序的基目录
string path = System.AppDomain.CurrentDomain.BaseDirectory;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\
5. 获取和设置包括该应用程序的目录的名称
string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\
6. 获取启动了应用程序的可执行文件的路径
string path = System.Windows.Forms.Application.StartupPath;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
7. 获取启动了应用程序的可执行文件的路径及文件名
string path = System.Windows.Forms.Application.ExecutablePath;
Debug.Print(path);

输出:C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.EXE

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.Append("System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:" + path1);
str.Append("System.Environment.CurrentDirectory:" + path2);
str.Append("System.IO.Directory.GetCurrentDirectory():" + path3);
str.Append("System.AppDomain.CurrentDomain.BaseDirectory:" + path4);
str.Append("System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:" + path5);
str.Append("System.Windows.Forms.Application.StartupPath:" + path6);
str.Append("System.Windows.Forms.Application.ExecutablePath:" + path7);
string allPath = str.ToString();
Debug.Print(allPath);
View Code

输出运行结果:
1.System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.vshost.exe
2.System.Environment.CurrentDirectory:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
3.System.IO.Directory.GetCurrentDirectory():
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
4.System.AppDomain.CurrentDomain.BaseDirectory:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
5.System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
6.System.Windows.Forms.Application.StartupPath:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug
7.System.Windows.Forms.Application.ExecutablePath:
C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.EXE
————————————————


原文链接:https://blog.csdn.net/mwl093/article/details/126659393

 

https://blog.csdn.net/nahuangtufunuo4852/article/details/122997217

 

1.获取包含清单的已加载文件的路径或 UNC 位置。
public static string sApplicationPath = Assembly.GetExecutingAssembly ( ).Location;
//result: X:\xxx\xxx\xxx.dll (.dll文件所在的目录+.dll文件名)
1
2
2.获取当前进程的完整路径,包含文件名(进程名)。
string str = this.GetType ( ).Assembly.Location;
//result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)
1
2
3.获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。
string str = System.Diagnostics.Process.GetCurrentProcess ( ).MainModule.FileName;
//result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)
1
2
4.当前工作目录,也就是cmd中>前面的的位置
//获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
string str = System.Environment.CurrentDirectory;
//result: X:\xxx\xxx (.exe文件所在的目录)
//获取应用程序的当前工作目录(不可靠)。
string str = System.IO.Directory.GetCurrentDirectory ( );
//result: X:\xxx\xxx (.exe文件所在的目录)
1
2
3
4
5
6
5.获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。
string str = System.AppDomain.CurrentDomain.BaseDirectory;
//result: X:\xxx\xxx\ (.exe文件所在的目录+"\")
1
2
6.获取和设置包含该应用程序的目录的名称。
 string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
//result: X:\xxx\xxx\ (.exe文件所在的目录+"\")
1
2
7.获取启动了应用程序的可执行文件的路径
//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string str = System.Windows.Forms.Application.StartupPath;
//result: X:\xxx\xxx (.exe文件所在的目录)
//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string str = System.Windows.Forms.Application.ExecutablePath;
//result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)
在系统服务中最好用这个方式去取路径
1
2
3
4
5
6
7
由路径获得文件夹路径
string stmp = Assembly.GetExecutingAssembly().Location;
stmp = stmp.Substring(0, stmp.LastIndexOf('\\'));//删除文件名
if (pathType == 1)
    return stmp + @"\inputLog.xml";
else if (pathType == 2)
    return stmp + @"\MiddleDB.xml";
else
    return stmp + @"\AppNo.xml";
1
2
3
4
5
6
7
8
由路径获得文件(夹)名
using System.IO;
string path = "d:asdfasdf.bmp";
string fileName = Path.GetFileName(path); //文件名
string ext = Path.GetExtension(path); //扩展名
string fileName = path。Substring(path.LastIndexOf(@"\") + 1);
1
2
3
4
5
常用操作
1、判定一个给定的路径是否有效,合法
通过Path.GetInvalidPathChars或Path.GetInvalidFileNameChars方法获得非法的路径/文件名字符,可以根据它来判断路径中是否包含非法字符;

2、如何确定一个路径字符串是表示目录还是文件
使用Directory.Exists或File.Exist方法,如果前者为真,则路径表示目录;如果后者为真,则路径表示文件
上面的方法有个缺点就是不能处理那些不存在的文件或目录。这时可以考虑使用Path.GetFileName方法获得其包含的文件名,如果一个路径不为空,而文件名为空那么它表示目录,否则表示文件;

3、获得路径的某个特定部分
Path.GetDirectoryName :返回指定路径字符串的目录信息。
Path.GetExtension :返回指定的路径字符串的扩展名。
Path.GetFileName :返回指定路径字符串的文件名和扩展名。
Path.GetFileNameWithoutExtension :返回不具有扩展名的路径字符串的文件名。
Path.GetPathRoot :获取指定路径的根目录信息。

4、准确地合并两个路径而不用去担心那个烦人的“\”字符
使用Path.Combine方法,它会帮你处理烦人的“\”。

5、获得系统目录的路径
Environment.SystemDirectory属性:获取系统目录的完全限定路径
Environment.GetFolderPath方法:该方法接受的参数类型为Environment.SpecialFolder枚举,通过这个方法可以获得大量系统 文件夹的路径,如我的电脑,桌面,系统目录等
Path.GetTempPath方法:返回当前系统的临时文件夹的路径

6、判断一个路径是绝对路径还是相对路径
使用Path.IsPathRooted方法

7、读取或设置当前目录
使用Directory类的GetCurrentDirectory和SetCurrentDirectory方法

8、使用相对路径
设置当前目录后(见上个问题),就可以使用相对路径了。对于一个相对路径,我们可以使用Path.GetFullPath方法获得它的完 全限定路径(绝对路径)。
注意:如果打算使用相对路径,建议你将工作目录设置为各个交互文件的共同起点,否则可能会引入一些不易发现的安全隐患,被恶意用户利用来访问系统文件。

9、文件夹浏览对话框(FolderBrowserDialog类)
主要属性: Description:树视图控件上显示的说明文本,如上图中的“选择目录–练习”;RootFolder:获取或设置从其开始浏览的根文件夹,如上图中设置的我的电脑(默认为桌面);SelectedPath:获取或设置用户选定的路径,如果设置了该属性,打开对话框时会定位到指定路径,默认为根文件夹,关闭对话框时根据该属性获取用户用户选定的路径; ShowNewFolderButton:获取或设置是否显示新建对话框按钮;
主要方法: ShowDialog:打开该对话框,返回值为DialogResult类型值,如果为DialogResult.OK,则可以由SelectedPath属性获取用户选定的路径;

另一个总结
1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName-获取模块的完整路径。
2.System.Environment.CurrentDirectory-获取和设置当前目录(该进程从中启动的目录)的完全限定目录。
3.System.IO.Directory.GetCurrentDirectory()-获取应用程序的当前工作目录。这个不一定是程序从中启动的目录,有可能程序放在C:\xxx里,这个函数有可能返回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\";
}
1
2
3
4
5
6
7
8
9
这样如果我们写了一个类库,类库中用到了Assembly.LoadFrom,由于是通用类库,所以可能用到Windows程序中也可能用到Web中,那么用上面的代码就很方便了.

Server.MapPath
System.Windows.Forms.StartupPath
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的引用后使用。

Environment.SpecialFolder特殊文件夹
// ApplicationData目录,它用作当前漫游用户的应用程序特定数据的公共储存库。 
// CommonApplicationData 目录,它用作所有用户使用的应用程序特定数据的公共储存库。 
// LocalApplicationData 目录,它用作当前非漫游用户使用的应用程序特定数据的公共储存库。 
// Cookies 用作Internet Cookie 的公共储存库的目录。 
// Desktop 逻辑桌面,而不是物理文件系统位置。 
// Favorites 用作用户收藏夹项的公共储存库的目录。 
// History 用作Internet 历史记录项的公共储存库的目录。 
// InternetCache 用作Internet 临时文件的公共储存库的目录。 
// Programs 包含用户程序组的目录。 
// MyComputer “我的电脑”文件夹。  
// MyMusic “My Music”文件夹。 
// MyPictures “My Pictures”文件夹。 
// Recent 包含用户最近使用过的文档的目录。 
// SendTo 包含“发送”菜单项的目录。 
// StartMenu 包含“开始”菜单项的目录。 
// Startup 对应于用户的“启动”程序组的目录。 
// System “System”目录。 
// Templates 用作文档模板的公共储存库的目录。 
// DesktopDirectory 用于物理上存储桌面上的文件对象的目录。 
// Personal 用作文档的公共储存库的目录。 
// MyDocuments “我的电脑”文件夹。 
// ProgramFiles “Program files”目录。 
// CommonProgramFiles 用于应用程序间共享的组件的目录。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
判断文件夹是否存在,创建、删除文件夹
if (System.IO.Directory.Exists(Server.MapPath("file")) == false)//如果不存在就创建file文件夹
{
  System.IO.Directory.CreateDirectory(Server.MapPath("file"));
}

System.IO.Directory.Delete(Server.MapPath("file"),true);//删除文件夹以及文件夹中的子目录,文件 

if (Directory.GetFiles(@"文件夹路径").Length == 0)
1
2
3
4
5
6
7
8
判断文件是否存在,文件移动位置
DirectoryInfo di = new DirectoryInfo(ProcessingDirectory);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
}
 if (System.IO.File.Exist(Server.MapPath("~/Back/Data.xml")))
{
//存在文件
} 
else
{
//不存在文件
   Directory.Create(Server.MapPath("~/Back/Data.xml"));//创建该文件
}

file.MoveTo(Path.Combine(destFolder, file.Name));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
winform提示框
if (MessageBox.Show("确认删除?", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)  
{

}
View Code