我有 GetItemText 的列表框问题,替换它并将其添加到列表中

I have a listbox issue with GetItemText, Replace it and Add it to the list

首先抱歉我的英语不好,但我是意大利人。

其次,我只从 4 个月开始编程,我很糟糕...

所以,我用 Windows 表格做了一个音乐播放器,你可以打开一个有音乐文件的文件夹并听它们,所以当它打开文件夹时,它会把所有文件放在列表框,但它们就像“C:\Desktop\Folder\AllStar.mp3”,我只希望它像“AllStar.mp3”,所以我编写了这段代码 但是当我 运行 它时,它创建了一个东西,在意大利语中它的 (Raccolta) [with google translator is (Collection) or (Gathering)] 并且它没有给我替换文件的短名称 ,我该如何解决?

这是代码

string text = listBox1.GetItemText(listBox1.Items);
text = text.Replace(@"C:\Users\****\****\Desktop\-PC-\Musica", "");
listBox1.Items.Add(text);

会有很大帮助!

您可以使用 Path.GetFileName 只检索没有扩展名的文件名。

完整示例

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace ListBoxExample
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void BrowseButton_Click(object sender, EventArgs e)
        {
            using (var browser = new FolderBrowserDialog())
            {
                DialogResult result = browser.ShowDialog();

                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(browser.SelectedPath))
                {
                    var files = Directory
                        .GetFiles(browser.SelectedPath)
                        .Where(path => Path.GetExtension(path).ToUpper().EndsWith("MP3"))
                        .Select(path => Path.GetFileName(path));

                    foreach (var file in files)
                    {
                        MusicListBox.Items.Add(file);
                    }
                }
            }
        }
    }
}