【发布时间】:2017-09-21 04:58:08
【问题描述】:
我想要做的是我有一个listBox,它显示一个文件夹中的所有.txt 文件,但我希望能够单击listBox 中的一个.txt 并让我的richTextBox 显示该 .txt 文件中的文本。
显示文件的代码:
private void Scripts_Load(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(@"scripts");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
list.Items.Add(file.Name);
}
至于textBox 中显示的代码,我尝试了很多互联网答案,但主要错误是Argument 1: cannot convert from 'object' to 'string'
我得到的最接近的是这个
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
//Read the file to a string
string FileBuffer = FileRead.ReadToEnd();
//set the rich text boxes text to be the file
richTextBox.Text = FileBuffer;
//Close the stream so the file becomes free!
FileRead.Close();
它崩溃说:`System.InvalidCastException:'无法将'System.String'类型的对象转换为'System.IO.FileInfo'类型。'
已经有评论说发生了这种情况,那个人回答说将第 1 行更改为 FileInfo SelectedFileInfo = new FileInfo(listBox1.SelectedItem);这个失败的说法Argument 1: cannot convert from 'object' to 'string'
`
我做到了耶!!!
private async void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = list.SelectedItem.ToString();
richTextBox1.Text = value1;
using (StreamReader sr = new StreamReader("scripts\\" + value1))
{
{
String line = await sr.ReadToEndAsync();
richTextBox1.Text = line;
}
}
}
【问题讨论】:
-
至于在文本框中显示的代码你提到了代码和错误,你能把它也添加到你的问题中吗?
-
你试过什么?你能分享那部分吗?哪一行抛出了这个异常?
-
我还尝试了其他一些我从未想过会起作用的东西。在大多数情况下,它确实有效,但结果错误(它会列出文件名或类似名称)。
标签: c# listbox richtextbox streamreader