为了账号安全,请及时绑定邮箱和手机立即绑定

C# 使用 StreamReader 读取几行?

C# 使用 StreamReader 读取几行?

C#
繁星淼淼 2022-08-20 14:51:29
我是C#的新手,我有一个问题。我希望将文件的内容写入RichTextBox,但该方法仅读取第一行。StreamReader.ReadLine我该如何解决这个问题?
查看完整描述

2 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

可能最简单的方法是使用类的方法:System.IO.FileReadAllText

myRichTextBox.Text = File.ReadAllText(filePath);

此类具有一堆静态方法,这些方法可以为您包装类,使读取和写入文件变得非常容易。StreamReader


查看完整回答
反对 回复 2022-08-20
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

有几种方法可以读取文件。如果你想用StreamReader来阅读它,并想读取整个文件,这可能是一个解决方案:


using System;

using System.IO;


class Test 

{

    public static void Main() 

    {

        try 

        {

            // Create an instance of StreamReader to read from a file.

            // The using statement also closes the StreamReader.

            using (StreamReader sr = new StreamReader("TestFile.txt")) 

            {

                string line;

                // Read and display lines from the file until the end of 

                // the file is reached.

                while ((line = sr.ReadLine()) != null) 

                {

                    Console.WriteLine(line);

                }

            }

        }

        catch (Exception e) 

        {

            // Let the user know what went wrong.

            Console.WriteLine("The file could not be read:");

            Console.WriteLine(e.Message);

        }

    }

}

您可以在控制台的输出发生时编辑该部分。在这里,可以将RichTextbox的字符串与


text += Environment.NewLine + line;


查看完整回答
反对 回复 2022-08-20
  • 2 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号