c#中如何在文本框中显示txt文档

txt文档中有多条内容,现在做到的是能够显示文档中的所有内容,但是不能够逐条显示,我的程序如写:
private void btnReadTxtStr_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("C:\\temp.txt", System.Text.Encoding.Default))
{
string TextStr;
TextStr = sr.ReadToEnd().ToString();
sr.Close();
this.txtReadTxtStr.Text = TextStr;
}
但不知道如何改动?

(1)在Visual Studio 中新建一个“Windows窗体应用程序”项目

(2)在Form1上布置一个TextBox 并将Multiline属性设置为true;ScrollBars属性设置为both

(3)窗体代码Form1.cs

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ReadTextFile(@"d:\sample.txt");   
        }
        /// <summary>
        /// 读入文本文件并在TextBox中显示
        /// </summary>
        /// <param name="filePath">文本文件名</param>
        private void ReadTextFile(string filePath)
        {
            // 读入文本文件的所有行
            string[] lines = File.ReadAllLines(filePath);
            // 在textBox1中显示文件内容
            foreach (string line in lines)
            {
                textBox1.AppendText(line + Environment.NewLine);
            }
        }
    }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-01-06

(1)在Visual
Studio
中新建一个“Windows窗体应用程序”项目
(2)在Form1上布置一个TextBox
并将Multiline属性设置为true;ScrollBars属性设置为both
(3)窗体代码Form1.cs
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ReadTextFile(@"d:\sample.txt");   
        }
        /// <summary>
        /// 读入文本文件并在TextBox中显示
        /// </summary>
        /// <param name="filePath">文本文件名</param>
        private void ReadTextFile(string filePath)
        {
            // 读入文本文件的所有行
            string[] lines = File.ReadAllLines(filePath);
            // 在textBox1中显示文件内容
            foreach (string line in lines)
            {
                textBox1.AppendText(line + Environment.NewLine);
            }
        }
    }
}

第2个回答  2008-05-16
private void btnReadTxtStr_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("C:\\temp.txt", System.Text.Encoding.Default))
{
string TextStr;
while((string t = sr.ReadLine())!=null)
{
TextStr=TextStr+t;
}
sr.Close();
this.txtReadTxtStr.Text = TextStr;
}
相似回答