从 C# 的列表框中的目录路径中去除前导字符

Strip leading characters from a directory path in a listbox in C#

所以我正在尝试自学 C#,我有一个我最初批量编写的程序,现在正尝试使用 WPF 在 C# 中重新创建。我有一个允许用户设置目录的按钮,然后选择的目录显示在列表框上方的文本框中,该列表框将每个子文件夹(仅第一级)添加到列表框。现在一切正常,但它会在列表框中写出整个目录路径。一个多小时以来,我一直在试图弄清楚如何从列表框条目中删除前导目录路径,但无济于事。这是我目前所拥有的:

    private void btn_SetDirectory_Click(object sender, RoutedEventArgs e)
    {
        //Create a folder browser dialog and set the selected path to "steamPath"
        var steamPath = new FolderBrowserDialog();
        DialogResult result = steamPath.ShowDialog();

        //Update the text box to reflect the selected folder path
        txt_SteamDirectory.Text = steamPath.SelectedPath;

        //Clear and update the list box after choosing a folder
        lb_FromFolder.Items.Clear();

        string folderName = steamPath.SelectedPath;
        foreach (string f in Directory.GetDirectories(folderName))
            {
                lb_FromFolder.Items.Add(f);
            }
    }

现在我尝试将最后一行更改为此,但它不起作用它只是使程序崩溃:

    foreach (string f in Directory.GetDirectories(folderName))
    {
        lb_FromFolder.Items.Add(f.Substring(f.LastIndexOf("'\'")));
    }

我相当确定 LastIndexOf 路线可能是正确的路线,但我走到了死胡同。如果这是一个愚蠢的问题,我深表歉意,但这是我第一次尝试使用 C#。提前致谢。

您可以使用此代码:

string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
  lb_FromFolder.Items.Add(f.Remove(0,folderName.Length));
}

这可以解决您的问题

 string folderName = steamPath.SelectedPath;
    foreach (string f in Directory.GetDirectories(folderName))
    {
       // string[] strArr = f.Split('\');
        lb_FromFolder.Items.Add(f.Split('\')[f.Split('\').Length-1]);
    }