C#编程:用Substring获取文件路径文件名扩展名
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
string strAll = openFileDialog1.FileName;
string strPath =
strAll.Substring(0, strAll.LastIndexOf("\\") + 1);
string strFileName=
strAll.Substring(strAll.LastIndexOf("\\")+1,
strAll.LastIndexOf(".")-
(strAll.LastIndexOf("\\")+1));
string strFileext =
strAll.Substring(strAll.LastIndexOf(".") + 1,
strAll.Length-strAll.LastIndexOf(".")-1
);
label1.Text = "文件路径: " + strPath;
label2.Text = "文件名称: " + strFileName;
label3.Text = "扩展名: " + strFileext;
}
}
小结:
IndexOf()和LastIndexOf() 如果没找到匹配字符返回-1;