[英]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.