C# 用StreamReader读几行?
我是新来C#的,我有个问题。我希望将文件内容写入RichTextBox,但是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读取该文件,
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代码>