[英]Displaying a text file on a Windows Form for C#
我正在尝试显示txt文件的内容。 我认为我应该为该方法使用RichTextBox。 我所做的就是这个。 但是,它不起作用。
public static byte[] ReadFile() {
FileStream fileStream = new FileStream(@"help.txt", FileMode.Open, FileAccess.Read);
byte[] buffer;
try {
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
} finally {
fileStream.Close();
}
return buffer;
}
private void richTextBox1_TextChanged(object sender, EventArgs e) {
ReadFile();
}
我可能丢失了一些内容,但看不到将读取结果附加到文本框的位置!
您正在返回缓冲区,但未在任何地方使用它。
您在这里遇到了一些问题。
我想richTextBox1_TextChanged与您要填充的RichTextBox的更改事件相关联。 这意味着除非您手动更改RichTextBox本身的内容,否则它不会执行。
此外,在该方法中,您正在调用一个方法(ReadFile),该方法读取您的文件并以byte []的形式返回内容,但是由于您始终不使用它,因此结果会丢失。
然后,即使您正在读取文件的方式也不正确,因为您一次读取了所有文件(您指定要读取文件中包含的确切字符数),所以不需要while循环。
我将附加到表单的load事件并编写如下内容:
public string FillRichText(string aPath)
{
string content = File.ReadAllText(aPath);
richTextBox1.Text = content;
}
private void Form1_Load(object sender, EventArgs e)
{
FillRichText(@"help.txt");
}
您将在表单的InitializeComponent()中使用以下行:
this.Load += new System.EventHandler(this.Form1_Load);
做这个:
有一个按钮。
单击按钮时,调用ReadFile(),将从ReadFile()接收到的byte []转换为字符串并显示在TextBox中。
用这个:
在表单的构造函数中,编写以下代码:
public Form1()
{
InitializeComponent(); // This should already be there by default
string content = File.ReadAllText(@"help.txt");
richTextBox1.Text = content;
}
这会一次性读取给定文件中的所有文本,并将其分配给富文本框。 在方法中读取文本时,您不会将结果byte
数组转换为字符串,也不会将其分配给富文本框。 仅仅读取文件将无济于事。
请同时删除TextChanged
事件:每次更改富文本框中的文本时,都会调用TextChanged
事件。 将新值设置为Text
属性时,也会发生这种情况,这将导致无限递归。 此外,当文本一开始没有更改时,永远不会调用此事件,因此您必须在富文本框中手动输入文本才能触发此事件。
将方法更改为以下内容, 不需要富文本框 ,可以使用一个简单的文本框来达到目的。
public void ReadFile() {
TextReader reder = File.OpenText(@"help.txt");
textBox1.Text = reder.ReadToEnd();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
richTextBox1.Text = File.ReadAllText(label1.Text);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.