我正在尝试显示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();
}发布于 2012-05-22 17:15:36
这里有几个问题。
我假设richTextBox1_TextChanged与您想要填充的RichTextBox的changed事件相关联。这意味着除非手动更改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);发布于 2012-05-22 17:01:29
我可能遗漏了一些东西,但我不知道您将读取结果添加到文本框的位置!
您正在返回buffer,但没有在任何地方使用它。
发布于 2012-05-22 17:04:23
执行以下操作:
https://stackoverflow.com/questions/10698799
复制相似问题