C# 如何将文本从文本文件复制到richbox?

C# 如何将文本从文本文件复制到richbox?,c#,C#,我想在加载表单时将.txt文件中的文本复制到richbox中。 我不想打开一个对话框来选择文件,只是自动打开一个特定的文件 Stream sr; OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if ((sr =

我想在加载表单时将.txt文件中的文本复制到richbox中。 我不想打开一个对话框来选择文件,只是自动打开一个特定的文件

 Stream sr;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            if ((sr = openFileDialog1.OpenFile()) != null)
            {
                string strfilename = openFileDialog1.FileName;
                string commandstext = File.ReadAllText(strfilename);
                richTextBox2.Text=commandstext;
            }
        }

你也可以按照其他两个答案中的建议去做

其他
更快
方式如下:


您面临什么
错误/问题
?这是打开文件对话框的方法。但我不想打开文件对话框,我不知道如何让表单在加载时自动复制richbox中该文本文件的文本。默认路径是什么?我指的是project/debug/?用于exe位置路径
string strfilename=System.IO.path.Combine(AppDomain.CurrentDomain.BaseDirectory,“文件名”)如果我想每次修改“特定文本文件”中的文本,我加载的表单会自动加载文本吗?就像编辑实时文本文件一样,表单会自动加载我在该文本文件中写入的内容。@DonTzapone如果要根据对源文件所做的更改动态刷新,则需要更多内容。您将看到文件系统监视程序!使用“Using”(使用)将在您完成文件操作后关闭该文件。defaut文件路径是什么?我的意思是在调试的应用程序文件夹中?我认为默认的是您的bin文件夹,但您可以尝试此操作以获取应用程序文件夹:AppDomain.CurrentDomain.BaseDirectory
    Stream sr;
    string strfilename = "PATH TO FILE"; //Code should know the path already
    string commandstext = File.ReadAllText(strfilename);
    richTextBox2.Text=commandstext;
void LoadFileToRTB(string fileName, RichTextBox rtb)
{
  rtb.LoadFile(File.OpenRead(fileName), RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
  // or
  rtb.LoadFile(fileName);
  // or
  rtb.LoadFile(fileName, RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
}
        using (StreamReader sr = new StreamReader("YourFilePath.txt"))
        {
            String line = sr.ReadToEnd();
            richTextBox2.Text=line;
        }