How do I show the filename in listbox but keep the

2019-04-15 20:48发布

I am making a program in which the user needs to load in multiple files. However, in the ListBox I need to show only file names of the files they loaded but still be able to use the files loaded. So I want to hide the full path. This is how I load a file into the ListBox now, but it shows the whole path:

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条回答
何必那么认真
2楼-- · 2019-04-15 21:29

You can extract the fileName of the absolute path using the static Class Path in the System.IO namespace

//returns only the filename of an absolute path.

Path.GetFileName("FilePath");
查看更多
ら.Afraid
3楼-- · 2019-04-15 21:40
// 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);
        }
    }
查看更多
登录 后发表回答