C# 如何去掉文件名后缀

来源:百度知道 编辑:UC知道 时间:2024/09/28 08:11:39
基于.net平台的网站开发,C#语言
现在已经实现能够从指定文件夹里读取文件的名称,然后作为listbox的数据项,但是现在出现在listbox里的是包含后缀名称的
我读取的是图片,所以最终显示出来的都带有.jpg
所以希望能够帮忙看看我的代码
怎样能够让后缀不显示出来
非常感谢!

protected void ListBox1_Load(object sender, EventArgs e)
{
//取文件夹路径
DirectoryInfo di = new DirectoryInfo("M:/img");
FileInfo[] diArr = di.GetFiles("*.jpg");
foreach (FileInfo dir in diArr)
{
//取文件路径
str1[++i] = dir.FullName;
//取文件名称
str[i] = dir.Name;
//将名称添加到listbox的选项中,是带有.jpg的
ListBox1.Items.Add(str[i]);

}
//Image控件的初始化
this.Image1.ImageUrl = str1[1];

}
不行啊!我按照你们的方法试了可是总是出现错误
就是采用name.Name.LastIndex(".")
但是提示
string 并不包含lastindex定义
怎么解决阿?

稍微做一下修改就行.
str[i] = dir.Name.Remove(dir.Name.LastIndex("."));

protected void ListBox1_Load(object sender, EventArgs e)
{
//取文件夹路径
DirectoryInfo di = new DirectoryInfo("M:/img");
FileInfo[] diArr = di.GetFiles("*.jpg");
foreach (FileInfo dir in diArr)
{
//取文件路径
str1[++i] = dir.FullName;
//取文件名称
str[i] = dir.Name;
//将名称添加到listbox的选项中,是带有.jpg的
ListBox1.Items.Add(str[i].Remove(dir.Name.LastIndexOf(".")););

}
//Image控件的初始化
this.Image1.ImageUrl = str1[1];

}

上述回答人的LastIndex都改为LastIndexOf

把最后一个点的后面全部拿掉就好了