-2
 private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string txt = "";
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text File|*.txt";
            ofd.FileName = "File";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {

                StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));

                while (txt != null) {



                    txt += sr.ReadLine() + "\n";
                    if (txt != null) richTextBox1.Text += txt;
                    else sr.Dispose();

                }

            }

        }

这是我的代码,旨在在单击“菜单条”项打开时运行。但不知何故,这会卡在我的应用程序上。代码中的错误是什么?

4

2 回答 2

2

您正在附加到 txt 所以它永远不能为空尝试

   string line;
   while ((line = sr.ReadLine()) != null)
   {
      txt += line + "\n";
      if (txt != null) richTextBox1.Text += txt;
      else sr.Dispose(); // Remove after seeing below
   }

此外,您应该始终处理您的流读取器,因此像这样包装您的 while 循环(也替换流读取器行)

using(StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName)))
{
//While loop here
}
于 2013-06-22T14:10:17.380 回答
0

您的代码中的直接错误是在循环条件中:

  while (txt != null)

由于 txt 不为空,您的应用程序陷入无限循环。还有一些其他问题:

  1. 您应该始终处置 IDisposable(代码中的 StreamReader)
  2. 不要添加到字符串,使用 StringBuilder

因此,如果您想将文件逐行读取到 RichEdit 中,您可以这样做

  OpenFileDialog ofd = new OpenFileDialog();
  ofd.Filter = "Text File|*.txt";
  ofd.FileName = "File";

  StringBuilder Sb = new StringBuilder();

  if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    using (StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName))) {
      while (!sr.EndOfStream)
        if (Sb.Length > 0) {
          Sb.AppendLine();
          Sb.Append(sr.ReadLine());
        }
        else
          Sb.Append(sr.ReadLine());
    }

    richTextBox1.Text += Sb.ToString();
  }
于 2013-06-22T14:18:41.440 回答