我希望在加载表单时将.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;
}
}
答案 0 :(得分:2)
您也可以按照其他2个答案中的建议进行操作。
或其他 faster
方式为:
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
}
答案 1 :(得分:0)
Stream sr;
string strfilename = "PATH TO FILE"; //Code should know the path already
string commandstext = File.ReadAllText(strfilename);
richTextBox2.Text=commandstext;
答案 2 :(得分:0)
using (StreamReader sr = new StreamReader("YourFilePath.txt"))
{
String line = sr.ReadToEnd();
richTextBox2.Text=line;
}