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

标签 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);
    }
}

最佳答案

// 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);
        }
    }

关于c# - 如何在列表框中显示文件名但使用 openfiledialog 保留相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273603/

相关文章:

javascript - 拖放到数据库 mvc 后保存图像顺序

C# 对象初始值设定项 - 包括构造函数调用括号?

c# - 需要快速的.NET ftp客户端

c# - 更改后 View 不刷新

delphi - 自定义 TAdvSmoothListBox 项目颜色

c# - 选择列表框中的所有复选框未正确显示

Avalonia 中的 OpenFileDialog - ShowAsync 出错

c# - 如何为 OpenFileDialog 框中的取消按钮编写代码

ms-access - 如何从 VBA 中的文件对话框对象中获取单个文件名(对于 MS Access 2007)?

.net - 在 WPF/Silverlight ListBox 中的项目之间添加空格,第一个上方或最后一个下方没有空格