加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#Visual Studio – 我正在尝试读取文本文件并将其显示在Richtex

发布时间:2020-12-16 10:06:11 所属栏目:百科 来源:网络整理
导读:我正在尝试读取文本文件并将其显示在Richtextbox中并包含新行. 说我希望它读作: 你好 你好 你好 但它的读数如下: 你好你好你好 这是我到目前为止的代码: private void btnView_Click(object sender,EventArgs e){ OpenFileDialog op = new OpenFileDialog
我正在尝试读取文本文件并将其显示在Richtextbox中并包含新行.
说我希望它读作:

你好

你好

你好

但它的读数如下:
你好你好你好

这是我到目前为止的代码:

private  void btnView_Click(object sender,EventArgs e)
{
    OpenFileDialog op = new OpenFileDialog();
    op.InitialDirectory = "C:";
    op.Filter = "Txt files (*.txt)|*.txt|All Files (*.*)|*.*";
    op.FilterIndex = 2;

    if (op.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = op.FileName;
        string path = op.FileName;
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(path)) 
        {
            while(sr.Peek() >= 0)
            {
                sb.Append(sr.ReadLine());
                Console.WriteLine("rn");
            }
        }

        richTextBox1.Text = sb.ToString();                
    }
}

解决方法

StreamReader行由Environment.NewLine分隔.如果您阅读了 documentation,您会注意到ReadLine不包含这些分隔符.如果要重新添加它们,请使用:

sb.Append(sr.ReadLine());
sb.Append(Environment.NewLine);

并且不要在WinForms应用程序中调用Console.WriteLine().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读