从列表框中删除文件扩展名和位置
本文关键字:扩展名 位置 文件 删除 列表 | 更新日期: 2023-09-27 18:18:12
我在c#中制作一个mp3播放器,我使用自动加载功能,它可以完美地加载和播放,但是"问题"出现在。mp3文件显示的列表框中。它显示的文件目录和文件扩展名如下所示:
C:'Users'Felix'Documents'songs_here'list_1'Admiral P - Engle.mp3
我想用
来代替Admiral P - Engel
这是可能的,我怎么做?文件加载代码为:
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
listBox1.Items.Add(file);
}
PopulateListBox1(dir1);
提前感谢!!
可以使用Path.GetFileNameWithoutExtension。
例如:路径。GetFileNameWithoutExtension方法(String)
返回指定路径字符串的文件名,不带扩展名。
Path.GetFileNameWithoutExtension("C:'Users'...'songs_here'list_1'Admiral P - Engle.mp3");
将返回:
海军上将p -恩格尔
更新:
我从你的评论中假设你想要显示文件名,但仍然有一个文件路径的引用来传递给你的播放器。
需要创建自己的类来保存mp3文件名和路径,如下所示:
public class MusicFile
{
public string Path;
public string FileName;
public override string ToString()
{
return FileName;
}
}
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
{
var music = new MusicFile
{
Path = file,
FileName = Path.GetFileNameWithoutExtension(file)
};
listBox1.Items.Add(music);
}
}
这展示了如何循环遍历每个项目并获得路径,但是您也可以根据需要使用诸如SelectedIndexChanged
之类的事件。
foreach (var item in listBox1.Items)
{
var filepath = ((MusicFile)item).Path; // Shows the full path, pass this to the player
}
使用Linq一行代码
private void PopulateListBox1(string folder)
{
listBox1.DataSource =Directory.GetFiles(folder).Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
}
作为文件命名模式是相同的,首先您可能希望在每个文件条目上使用字符串分割点字符来检查文件扩展名,然后对于每个文件,如果它是mp3扩展名,分割并弹出最后一个单词