[英]C# Read several lines with StreamReader?
I'm new to C# and I have a problem. 我是C#的新手,但是有问题。 I would like to have the content of a file written to a RichTextBox, but the
StreamReader.ReadLine
method reads only the first line. 我想将文件的内容写入RichTextBox,但是
StreamReader.ReadLine
方法仅读取第一行。
How can I solve this? 我该如何解决?
Probably the easiest way to do this would be to use the System.IO.File
class's ReadAllText
method: 可能最简单的方法是使用
System.IO.File
类的ReadAllText
方法:
myRichTextBox.Text = File.ReadAllText(filePath);
This class has a bunch of static methods that wrap the StreamReader
class for you that make reading and writing to files quite easy. 此类具有许多静态方法,这些方法可以为您包装
StreamReader
类,从而使读取和写入文件变得非常容易。
There are several ways to read a file. 有几种读取文件的方法。 If you want to it with a StreamReader and want to read the whole file, this could be a solution:
如果要使用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);
}
}
}
You could edit the part were the output of the console happens. 您可以编辑发生控制台输出的部分。 Here it would be possible to concatenate the string for your RichTextbox with
在这里,可以将您的RichTextbox的字符串与
text += Environment.NewLine + line;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.