C# 之 获取文件名及拓展名

C# 之 获取文件名及拓展名

1、用Path类的方法(最常用)

string fullPath = @"WebSiteDefault.aspx";

string filename = System.IO.Path.GetFileName(fullPath);//带拓展名的文件名  “Default.aspx”
string extension = System.IO.Path.GetExtension(fullPath);//扩展名 “.aspx”
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fullPath);// 不带扩展名的文件名 “Default”
string dir = System.IO.Path.GetDirectoryName(fullPath);     //返回文件所在目录“\WebSite”

2、用Substring截取

string aFirstName = fullPath.Substring(fullPath.LastIndexOf("\") + 1, (fullPath.LastIndexOf(".") - fullPath.LastIndexOf("\") - 1));  //不带拓展名的文件名“Default”
string aLastName = fullPath.Substring(fullPath.LastIndexOf(".") + 1, (fullPath.Length - fullPath.LastIndexOf(".") - 1));   //扩展名“aspx”


string strFileName = fullPath.Substring(fullPath.LastIndexOf("\") + 1, fullPath.Length - 1 - fullPath.LastIndexOf("\"));//带拓展名的文件名  “Default.aspx”
string strExtensionName = fullPath.Substring(fullPath.LastIndexOf("."), fullPath.Length - fullPath.LastIndexOf("."));//扩展名 “.aspx”

3、用openFileDialog.SafeFileName,取到该文件的所在目录路径
string path1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"";

string path = Path.GetFileName("C:My Documentpathimage.jpg");    //只获取文件名image.jpg

4、进程相关

//获取当前进程的完整路径,包含文件名(进程名)。获取包含清单的已加载文件的路径或 UNC 位置。
string str0 = this.GetType().Assembly.Location;
//C:UsersyiyiAppDataLocalTempTemporary ASP.NET Fileswebd33ba98cbcc133aApp_Web_eidyl2kf.dll
//result: X:xxxxxxxxx.exe (.exe文件所在的目录+.exe文件名)

//获取新的 System.Diagnostics.Process 组件并将其与当前活动的进程关联
//获取关联进程主模块的完整路径,包含文件名(进程名)
string str1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
//C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0WebDev.WebServer40.exe
//result: X:xxxxxxxxx.exe (.exe文件所在的目录+.exe文件名)

//获取或设置当前工作目录(即该进程从中启动的目录)的完全限定路径。
string str2 = System.Environment.CurrentDirectory;
//C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0
//result: X:xxxxxx (.exe文件所在的目录)

//获取当前 System.Threading.Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。
string str3 = System.AppDomain.CurrentDomain.BaseDirectory;
//F:Code得利斯20150923web
//result: X:xxxxxx (.exe文件所在的目录+"")

//获取或设置包含该应用程序的目录的名称。
string str4 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
//F:Code得利斯20150923web
//result: X:xxxxxx (.exe文件所在的目录+"")

//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string str5 = System.Windows.Forms.Application.StartupPath;
//C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0
//result: X:xxxxxx (.exe文件所在的目录)

//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string str6 = System.Windows.Forms.Application.ExecutablePath;
//C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0WebDev.WebServer40.exe
//result: X:xxxxxxxxx.exe (.exe文件所在的目录+.exe文件名)

//获取应用程序的当前工作目录(不可靠)。
string str7 = System.IO.Directory.GetCurrentDirectory();
//C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0
//result: X:xxxxxx (.exe文件所在的目录)

原文地址:https://www.cnblogs.com/yuer20180726/p/10382421.html