Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用StreamReader读几行?_C#_Winforms_Richtextbox_Streamreader - Fatal编程技术网

C# 用StreamReader读几行?

C# 用StreamReader读几行?,c#,winforms,richtextbox,streamreader,C#,Winforms,Richtextbox,Streamreader,我是新来C#的,我有个问题。我希望将文件内容写入RichTextBox,但是StreamReader.ReadLine方法只读取第一行 如何解决此问题?最简单的方法可能是使用System.IO.File类的ReadAllText方法: myRichTextBox.Text = File.ReadAllText(filePath); 这个类有一系列静态方法,它们为您包装了StreamReader类,使文件的读写变得非常简单。有几种读取文件的方法。如果您希望使用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;

叫它不止一次。。?或者只使用
ReadToEnd
方法?对不起,谷歌翻译。有什么问题?可能是重复的?您如何知道要从文件中读取多少行?您是在读取固定数量的行,还是一直读取到终止字符,还是读取整个文件?请注意
text=text+line将从文件内容中删除所有换行符。您可以改为执行
text+=Environment.NewLine+line