嗯,是这里的几个选项,其中没有涉及分裂文本。
注:所有下面的代码是使用具有作为一个字符串的文件路径私有变量:使用Text
public partial class Form1 : Form
{
private const string filePath = @"f:\public\temp\temp.txt";
第一个是简单地保存所有的文字(包括\r\n
字符)财产,与File.ReadAllText
和File.WriteAllText
沿:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
richTextBox1.Text = File.ReadAllText(filePath);
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllText(filePath, richTextBox1.Text);
}
如果你想这样做,一行行,你可以使用File.ReadAllLines
和File.WriteAllLines
与一起在RichTextBox
的属性:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
richTextBox1.Lines = File.ReadAllLines(filePath);
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllLines(filePath, richTextBox1.Lines);
}
最后,你可以使用RichTextBox
类的内置SaveFile
和LoadFile
方法。这种方法将元数据写入文件,所以如果你在记事本中打开它,你会看到一些其他的字符,包括各种格式信息。正因为如此,我加入了通话围绕try/catch
块LoadFile
,因为它会引发和异常,如果该文件不具有正确的格式,我回落到加载它与ReadAllText
:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
try
{
richTextBox1.LoadFile(filePath);
}
catch (ArgumentException)
{
// Fall back to plain text method if the
// file wasn't created by the RichTextbox
richTextBox1.Text = File.ReadAllText(filePath);
}
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.SaveFile(filePath);
}
为了节省: 'richTextBox1.SaveFile(fileName);'加载:'richTextBox1.LoadFile(fileName);' – LarsTech