Welcome

首页 / 软件开发 / C# / C#从字符串中分离文件路径、文件名及扩展名

C#从字符串中分离文件路径、文件名及扩展名2009-12-23开发程序时,为了更好的识别文件的相关属性,经常需要将文件的路径、名称及其扩展名从一个字符串中分离出来,这时可以使用Substring方法在字符串中进行相应的截取,然后输出即可。从字符串中分离文件路径、文件名及扩展名的关键代码如下:

string strPath = textBox1.Text.Substring(0, textBox1.Text.LastIndexOf("\"));
string strName=textBox1.Text.Substring(textBox1.Text.LastIndexOf("\")+1,(textBox1.Text.LastIndexOf(".")-textBox1.Text.LastIndexOf("\")-1) );
string strEName = textBox1.Text.Substring(textBox1.Text.LastIndexOf(".")+1, (textBox1.Text.Length - textBox1.Text.LastIndexOf(".")-1));
MessageBox.Show("文件路径:"+strPath +" 文件名:"+strName +" 文件扩展名:"+strEName ,"信息",MessageBoxButtons.OK,MessageBoxIcon.Information );