简体   繁体   English

C#-删除列表框项的一部分

[英]C# - remove part of listbox items

I have a ListBox which has a collection of files from a directory and I need to remove the extension from them. 我有一个ListBox ,其中有一个目录中的文件集合,我需要从中删除扩展名。 They will all be m4a format so that should make it a bit easier. 它们都将是m4a格式,因此应该更容易一些。 However I have searched and cannot find a solution. 但是,我已经搜索过,无法找到解决方案。

I am very new to programming and would appreciate some help. 我对编程非常陌生,希望能提供一些帮助。 If I could request an example I would really appreciate it and could you please use lstSong instead of a placeholder because I get confused as to whats a placeholder and not in examples. 如果我可以请求一个示例,我将不胜感激,请您使用lstSong而不是一个占位符,因为我对占位符(而不是示例)感到困惑。

As requested the code that writes to it: 根据要求写入的代码:

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);
}

I am unsure exactly how this code works. 我不确定该代码如何工作。 I understand most of it but it was written by a friend to help me. 我了解大多数内容,但是它是由一位朋友写的,可以帮助我。 Which is why i was going to do it afterwards. 这就是为什么我以后要这样做。 Thanks again. 再次感谢。

Understanding from your comment you only need the filename of the files, without the path or the extension. 从您的注释中了解,您只需要文件的文件名,而无需路径或扩展名。 For that you can use Path.GetFileNameWithoutExtension 为此,您可以使用Path.GetFileNameWithoutExtension

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
}

And to explain the code your friend has wrote: 并解释您朋友写的代码:

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

The string.Split method diviedes the string into an array of substrings delimited by the given character. string.Split方法将字符串分成由给定字符分隔的子字符串数组。 In this case it's an ( escaped ) backslash. 在这种情况下,它是一个( 转义的 )反斜杠。 The .Last() returns the last element of the array. .Last()返回数组的最后一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM