1

我正在制作一个程序,用户需要在其中加载多个文件。但是,在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);
    }
}
4

2 回答 2

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);
        }
    }
于 2012-04-23T01:26:50.303 回答
2

您可以使用in提取fileName绝对路径的static Class PathSystem.IO namespace

//returns only the filename of an absolute path.

Path.GetFileName("FilePath");
于 2012-04-23T01:47:21.953 回答