可以将 ReadAllText 与 listBox.SelectedItem 一起使用吗?



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

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

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'。

解决此问题的一种方法是将FileInfo对象的数组作为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());
}
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));
}
}
}
}

最新更新