嗯,是這裏的幾個選項,其中沒有涉及分裂文本。
注:所有下面的代碼是使用具有作爲一個字符串的文件路徑私有變量:使用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