簡體   English   中英

在列表框中獲取所選文件的當前文件夾名稱

[英]Get Current folder name of selected file in Listbox

我有一個TextBox來搜索主文件夾中的文件,它也有子文件夾。 我想在ListBox獲取所選項目的當前文件夾名稱,以顯示在另一個ListBox

我該怎么做呢?

我最近的努力:

這是我的完整編碼!!

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string path = @"C:\Users\guest\Desktop\test\";

        listBox2.Items.Clear();

        {
            listBox2.Items.Add(Path.GetDirectoryName(path));
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        DirectoryInfo sdir = new DirectoryInfo(@"C:\Users\guest\Desktop\test");
        FileInfo[] files = sdir.GetFiles(textBox1.Text.ToString() + "*", System.IO.SearchOption.AllDirectories);
        string search = "";

        listBox1.Items.Clear();

        foreach (FileInfo file in files)
        {
            search = file.Name;
            listBox1.Items.Add(Path.GetFileNameWithoutExtension(search));
        }
    }

必需的輸出標記為紅色,請參見下面的快照。

搜索文件名並獲取完整路徑 搜索文件名並獲取完整路徑

問題是,當您添加到listBox1您正在添加一個string -然后,它將丟失其原始路徑的上下文。 解決方案是改為添加一個object (例如TestPath )-該object可以將ToString放入所需的文本中, 但仍保留其原始路徑的上下文

下面可能會幫助您實現該目標。

添加此類:

public class TestPath
{
    public FileInfo Original { get; private set; }

    public TestPath(FileInfo original)
    {
        Original = original;
    }

    public override string ToString()
    {
        return Path.GetFileNameWithoutExtension(Original.Name);
    }
}

然后替換:

foreach (FileInfo file in files)
{
    search = file.Name;
    listBox1.Items.Add(Path.GetFileNameWithoutExtension(search));
}

與:

foreach (FileInfo file in files)
{
    var path = new TestPath(file);
    listBox1.Items.Add(path);
}

然后替換:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string path = @"C:\Users\guest\Desktop\test\";

    listBox2.Items.Clear();

    {
        listBox2.Items.Add(Path.GetDirectoryName(path));
    }
}

與:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox2.Items.Clear();

    var currentItem = listBox1.SelectedItem as TestPath;
    listBox2.Items.Add(currentItem.Original.FullName); // or any property
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM