猿问

C# 使用 StreamReader 读取几行?

我是C#的新手,我有一个问题。我希望将文件的内容写入RichTextBox,但该方法仅读取第一行。StreamReader.ReadLine

我该如何解决这个问题?


繁星淼淼
浏览 152回答 2
2回答

呼唤远方

可能最简单的方法是使用类的方法:System.IO.FileReadAllTextmyRichTextBox.Text = File.ReadAllText(filePath);此类具有一堆静态方法,这些方法可以为您包装类,使读取和写入文件变得非常容易。StreamReader

翻过高山走不出你

有几种方法可以读取文件。如果你想用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;
随时随地看视频慕课网APP
我要回答