繁体   English   中英

C#使用StreamReader读几行?

[英]C# Read several lines with StreamReader?

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

我该如何解决?

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

myRichTextBox.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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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