C#获取文件名和文件路径

方法一

1
2
3
4
5
OpenFileDialog open = new OpenFileDialog();
open.RestoreDirectory = true;
string fullname = open.FileName;
string path = System.IO.Path.GetDirectoryName(fullname);//路径
string name = System.IO.Path.GetFileName(fullname);//名称

方法二

1
2
3
4
5
6
7
OpenFileDialog open = new OpenFileDialog();
open.RestoreDirectory = true;
string fullpath = open.FileName;
//获取文件路径和文件名
int index = fullpath.LastIndexOf("//"); //返回“//”最后一次出现的位置
string filepath = fullpath.Substring(0,index); //截取字符串,0到“//”最后出现的位置
string filename = fullpath.Substring(index+1); //截取文件名

C#通过文件路径获取文件名小技巧

1
2
3
4
5
string fullPath = @"\WebSite1\Default.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”

相关链接(侵删)

  1. C#获取文件名和文件路径的两种实现方式

=================我是分割线=================

欢迎到公众号来唠嗑: