我只是想简单地在MyMusic文件夹中创建一个歌曲列表,并将它们显示在一个列表框中。字符串稍后也将用于语音命令,但添加这些命令不会有问题。我的问题是,尽管我尝试过,但无法从显示的名称中删除路径。
InitializeComponent();
string path = @"C:\Users\Toby\Music";
string[] Songs = Directory.GetFiles(path, "*.mp3", SearchOption.TopDirectoryOnly);
List<string> SongList = new List<string>();
int pathlngth = path.Length;
int i = 0;
string fix;
foreach (string Asong in Songs)
{
fix = Asong.Remove(0,pathlngth);
fix = Asong.Remove(Asong.Length-4);
SongList.Add(fix);
i = i + 1;
}
SongList.Add("");
SongList.Add("There are " + i + " songs");
SongBox.Datasource = SongList;至少对我来说,这是可行的。但是,来自我的Listbox的结果将如下所示:
等等..。你知道怎么回事吗?我终于删除了扩展。我试过用path.Length代替pathlngth,一点也不改变。
发布于 2014-05-10 20:08:01
从路径中获取FileName
string strSongName = System.IO.Path.GetFileName(FileFullPath);从路径中获取FileNameWithoutExtension
string sFileNameWithOutExtension = Path.GetFileNameWithoutExtension(FileFullPath);你的解决方案:
List<string> SongList = new List<string>();
string path = @"C:\Users\Toby\Music";
string[] Songs = Directory.GetFiles(path, "*.mp3", SearchOption.TopDirectoryOnly);
SongList.Add("");
SongList.Add("There are " + Songs.Length + " songs");
foreach (string Asong in Songs)
{
string sFileNameWithOutExtension = Path.GetFileNameWithoutExtension(Asong);
SongList.Add(sFileNameWithOutExtension);
}
SongBox.DataSource = SongList;发布于 2014-05-10 20:07:25
有一个API已经做到了- Path.GetFileName。
foreach (string song in Songs)
{
SongList.Add(System.IO.Path.GetFileName(song));
}这将为您提供名称+扩展名,如果您想省略扩展名,可以使用Path.GetFileNameWithoutExtension。
发布于 2014-05-10 20:07:39
您正在分配"fix“的值,然后立即覆盖它。
fix = Asong.Remove(0,pathlngth);
fix = Asong.Remove(Asong.Length-4);很可能是
fix = Asong.Remove(0,pathlngth);
fix = fix.Remove(Asong.Length-4);另一种选择是只使用Path.GetFileName(Asong);但是您仍然需要对它进行操作以删除扩展。
https://stackoverflow.com/questions/23585729
复制相似问题