如何在列表框中显示文件名但使用openfiledialog保留相对路径?

时间:2012-04-23 00:59:21

标签: c# listbox openfiledialog

我正在制作一个用户需要加载多个文件的程序。但是,在ListBox我需要只显示他们加载的文件的文件名,但仍然可以使用加载的文件。所以我想隐藏完整的路径。这就是我现在将文件加载到ListBox的方式,但它显示了整个路径:

private void browseBttn_Click(object sender, EventArgs e)
{
    OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
    OpenFileDialog1.Multiselect = true;
    OpenFileDialog1.Filter = "DLL Files|*.dll";
    OpenFileDialog1.Title = "Select a Dll File";
    if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        dllList.Items.AddRange(OpenFileDialog1.FileNames);
    }
}

2 个答案:

答案 0 :(得分:3)

// Set a global variable to hold all the selected files result
List<String> fullFileName;

// Browse button handler
    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
        OpenFileDialog1.Multiselect = true;
        OpenFileDialog1.Filter = "DLL Files|*.dll";
        OpenFileDialog1.Title = "Seclect a Dll File";
        if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            // put the selected result in the global variable
            fullFileName = new List<String>(OpenFileDialog1.FileNames);

            // add just the names to the listbox
            foreach (string fileName in fullFileName)
            {
                dllList.Items.Add(fileName.Substring(fileName.LastIndexOf(@"\")+1));
            }


        }
    }

    // handle the selected change if you wish and get the full path from the selectedIndex.
    private void dllList_SelectedIndexChanged(object sender, EventArgs e)
    {
        // check to make sure there is a selected item
        if (dllList.SelectedIndex > -1)
        {
            string fullPath = fullFileName[dllList.SelectedIndex];

            // remove the item from the list
            fullFileName.RemoveAt(dllList.SelectedIndex);
            dllList.Items.Remove(dllList.SelectedItem);
        }
    }

答案 1 :(得分:2)

您可以使用fileName

中的static Class Path提取绝对路径的System.IO namespace
//returns only the filename of an absolute path.

Path.GetFileName("FilePath");