C#-删除部分列表框项

本文关键字:列表 删除部 C#- | 更新日期: 2023-09-27 18:24:47

我有一个ListBox,它有一个目录中的文件集合,我需要从中删除扩展名。它们都将是m4a格式,所以应该会让它变得更容易一些。然而,我已经搜索过了,找不到解决方案。

我对编程很陌生,希望能给我一些帮助。如果我能要求一个例子,我真的很感激,你能用lstSong代替占位符吗?因为我对什么是占位符而不是在例子中感到困惑。

根据请求写入其中的代码:

string[] songspaths = System.IO.Directory.GetFiles(librarypath + "/" + albumpath + "/" + songpath);
List<string> listsongs = new List<string>();
foreach (var f in songspaths)
{
   string songs = f.Split('''').Last();
   lstSong.Items.Add(songs);
}

我不确定这个代码到底是如何工作的。我理解其中的大部分内容,但这是一个朋友帮我写的。这就是为什么我后来要这么做的原因。再次感谢。

C#-删除部分列表框项

从注释中了解您只需要文件的文件名,而不需要路径或扩展名。为此,您可以使用Path.GetFileName WithoutExtension

string[] songspaths = System.IO.Directory.GetFiles(librarypath + "/" + albumpath + "/" + songpath); // Get all the files from the specified directory
List<string> listsongs = new List<string>();
foreach (var f in songspaths)
{
   lstSong.Items.Add(Path.GetFileNameWithoutExtension(f)); // Store the filename without path or extension in the list
}

为了解释你朋友写的代码:

string songs = f.Split('''').Last();

字符串。Split方法将字符串分割成由给定字符分隔的子字符串数组。在这种情况下,它是一个(转义的)反斜杠。.Last()返回数组的最后一个元素。