-1

我在 Winforms 中有一个列表框,它显示我计算机上文件夹中的文本文件。当我在列表框中选择一个文件/项目时,我希望能够在文本框中看到文本文件的内容。

这是在我的列表框中显示目录的代码:

  private void Button1_Click(object sender, EventArgs e)
  {
      DirectoryInfo dInfo = new DirectoryInfo(@"c:\testing");
      FileInfo[] files = dInfo.GetFiles("*.txt");
      foreach (FileInfo file in files)
      {
          listBox1.Items.Add(file.Name);
      }
  }

然后我尝试显示所选文本文件的内容:

  private void Button2_Click(object sender, EventArgs e)
  {
      string curItem = listBox1.SelectedItem.ToString();
      string content = File.ReadAllText(curItem);
      textBox1.Text = content;
  }

显然最后一部分不起作用,因为我认为它需要所选文件的路径。但是,如果我事先不知道将在 listBox 上选择哪个文件,我该如何给它完整路径?

我得到的例外是(我想这并不奇怪):

System.IO.FileNotFoundException: '找不到文件'C:\Users\OldMan\source\repos\WindowsFormsTests\testing\bin\Debug\LICENSE.txt'。

4

2 回答 2

0
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;

namespace ListBox_57860008
{
    public partial class Form1 : Form
    {
        BindingList<FileInfo> lstbx_DataSource = new BindingList<FileInfo>();
        public Form1()
        {
            InitializeComponent();
            listBox1.DataSource = lstbx_DataSource;
            listBox1.DisplayMember = "Name";
            listBox1.SelectedIndexChanged += ListBox1_SelectedIndexChanged;
            fillDataSource();
        }

        private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = File.ReadAllText(((FileInfo)listBox1.SelectedItem).FullName);
        }

        private void fillDataSource()
        {
            foreach (string item in Directory.GetFileSystemEntries("c:\\temp\\", "*.txt"))
            {
                lstbx_DataSource.Add(new FileInfo(item));
            }
        }
    }
}
于 2019-09-09T19:37:18.533 回答
0

解决此问题的一种方法是将FileInfo对象数组作为 a添加DataSource到列表框中,并将"Name"属性设置为 ,DisplayMember并将完整路径 ( "FullName") 设置为ValueMember属性:

private void Button1_Click(object sender, EventArgs e)
{
    // Set the datasource property of the list box to the FileInfo array
    listBox1.DataSource = new DirectoryInfo(@"c:\testing").GetFiles("*.txt");

    // Set the display property as the file name and the value property as the file path
    listBox1.DisplayMember = "Name";
    listBox1.ValueMember = "FullName";
}

现在,列表框将显示文件名,但我们可以使用SelectedValue属性访问关联的路径(返回FullName所选项目的 ):

private void Button2_Click(object sender, EventArgs e)
{
    textBox1.Text = File.ReadAllText(listBox1.SelectedValue.ToString());
}
于 2019-09-09T19:44:15.723 回答