VB.NET / C# 从TXT文档中读取多行文本显示在 RichTextBox
还是先从最简单的开始来吧,基本来说就是两种方法,效果都一样,一个是直接将所有文本粘贴到 richTextBox 中,而另外一种方法则是以数组的形式将文本逐行保存,然后再依次写入 richTextBox 中。
C# 代码
方法1:利用 File.ReadAllText 读取所有文本内容放入 richTextBox 中(无换行问题)
1 2 | string str = File.ReadAllText(@"c:\temp\test.txt"); richTextBox1.Text = str; |
方法2:利用 File.ReadLines 逐行读取文本内容放入数组中,然后依次写入 richTextBox 中(需加换行符)
1 2 3 4 5 | string[] lines = File.ReadLines(@"c:\temp\test.txt").ToArray(); foreach (string s in lines) { richTextBox1.AppendText(s + "\r\n"); } |
方法3:利用 File.ReadAllLines 逐行读取文本内容放入数组中,然后依次写入 richTextBox 中(需加换行符)
1 2 3 4 5 6 | string[] readText = File.ReadAllLines(@"c:\temp\test.txt"); richTextBox1.Text = ""; foreach (string s in readText) { richTextBox1.AppendText(s + "\r\n"); } |
方法4:利用 StreamReader 读取所有文本内容放入 richTextBox 中(无换行问题)
1 2 3 4 | StreamReader str = new StreamReader(@"c:\temp\test.txt"); string s = str.ReadToEnd(); richTextBox1.Text = s; str.Close(); |
方法5:利用 StreamReader 逐行读取文本内容,然后循环依次写入 richTextBox 中(需加换行符)
1 2 3 4 5 6 7 | StreamReader sr = new StreamReader(@"c:\temp\test.txt"); string line; while ((line = sr.ReadLine()) != null) { richTextBox1.AppendText(line + "\r\n"); } sr.Close(); |
VB.NET
方法1:
1 2 | Dim readText As String = File.ReadAllText("c:\temp\test.txt") RichTextBox1.Text = readText |
方法2:
1 2 3 4 5 6 | Dim lines() As String = File.ReadLines("c:\temp\test.txt").ToArray() Dim s As String RichTextBox1.Text = "" For Each s In lines RichTextBox1.AppendText(s & vbLf) Next |
方法3:
1 2 3 4 5 6 | Dim lines() As String = File.ReadAllLines("c:\temp\test.txt") Dim s As String RichTextBox1.Text = "" For Each s In lines RichTextBox1.AppendText(s & vbLf) Next |
方法4:
1 2 3 4 | Dim sr As StreamReader = New StreamReader("c:\temp\test.txt") Dim line As String = sr.ReadToEnd() RichTextBox1.Text = line sr.Close() |
方法5:
1 2 3 4 5 6 7 | Dim sr As StreamReader = New StreamReader("c:\temp\test.txt") Dim line As String Do line = sr.ReadLine() RichTextBox1.AppendText(line & vbLf) Loop Until line Is Nothing sr.Close() |