简体   繁体   English

在Windows窗体上为C#显示文本文件

[英]Displaying a text file on a Windows Form for C#

I am trying to display the content of a txt file. 我正在尝试显示txt文件的内容。 I thought I should use RichTextBox for that method. 我认为我应该为该方法使用RichTextBox。 What I've done was this. 我所做的就是这个。 However it does not work. 但是,它不起作用。

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();
    }

I may be missing something but I don't see where you are appending the result of your read to the textbox! 我可能丢失了一些内容,但看不到将读取结果附加到文本框的位置!

You are returning buffer but not using it anywhere. 您正在返回缓冲区,但未在任何地方使用它。

You've got a couple of problems here. 您在这里遇到了一些问题。

I suppose that richTextBox1_TextChanged is associated with the changed event of the RichTextBox you want to fill. 我想richTextBox1_TextChanged与您要填充的RichTextBox的更改事件相关联。 This means that it isn't executed unless you manually change the content of the RichTextBox itself. 这意味着除非您手动更改RichTextBox本身的内容,否则它不会执行。

Furthermore in the method you are calling a method (ReadFile) which read your file and return the content as a byte[], but the result get lost since you aren't using it anyway. 此外,在该方法中,您正在调用一个方法(ReadFile),该方法读取您的文件并以byte []的形式返回内容,但是由于您始终不使用它,因此结果会丢失。

Then even the way you are reading the file is not correct, since you are reading all the file at once (you are specifying to read the exact number of characters contained in the file), so the while loop isn't needed. 然后,即使您正在读取文件的方式也不正确,因为您一次读取了所有文件(您指定要读取文件中包含的确切字符数),所以不需要while循环。

I would attach to the load event of the form and write something like this: 我将附加到表单的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");
}

You will need this line in the InitializeComponent() of your form: 您将在表单的InitializeComponent()中使用以下行:

this.Load += new System.EventHandler(this.Form1_Load);

Do this: 做这个:

  1. Have a button. 有一个按钮。

  2. On button click, call ReadFile(), convert byte[] received from ReadFile() to string and display in TextBox. 单击按钮时,调用ReadFile(),将从ReadFile()接收到的byte []转换为字符串并显示在TextBox中。

Use this: 用这个:

In the form's constructor, write the following code: 在表单的构造函数中,编写以下代码:

public Form1()
{
    InitializeComponent(); // This should already be there by default

    string content = File.ReadAllText(@"help.txt");
    richTextBox1.Text = content;
}

This reads all the text from the given file in one go and assigns it to the rich text box. 这会一次性读取给定文件中的所有文本,并将其分配给富文本框。 While you read the text in your method, you're not converting the resulting byte array to a string and you're also not assigning it to the rich text box. 在方法中读取文本时,您不会将结果byte数组转换为字符串,也不会将其分配给富文本框。 Simply reading the file won't help. 仅仅读取文件将无济于事。

Please remove the TextChanged event also: The TextChanged event is called every time the text in the rich text box is changed. 请同时删除TextChanged事件:每次更改富文本框中的文本时,都会调用TextChanged事件。 This is also the case when setting a new value to the Text property, which would cause an infinite recursion. 将新值设置为Text属性时,也会发生这种情况,这将导致无限递归。 Also, this event is never called when the text doesn't change in the first place, so you would have to enter text manually in the rich text box to fire this event. 此外,当文本一开始没有更改时,永远不会调用此事件,因此您必须在富文本框中手动输入文本才能触发此事件。

Change the method to the following and you don't need rich textbox , a simple textbox can serve the purpose. 将方法更改为以下内容, 不需要富文本框 ,可以使用一个简单的文本框来达到目的。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM