2017-10-20 234 views
0

例如在RichTextBox裏面我有文字:如何從richTextbox中讀取文本並保留文本的格式?

Hello world 
Hello hi 

Hi all 

現在我想讀這段文字用這種格式,包括空行/秒,然後用或不用寫回同一個文件相同的文本像刪除的文字或添加的文字一樣改變

例如,如果我刪除寫回將這種格式的所有再用文:

Hello world 
Hello hi 

Hi 

就沒有一切 或者

Hello world 
Hello hi 

Hi all everyone 

所以現在會寫的同樣的文字,但與每個人,但將保持格式。

我試過,但這個增加過多的空行和空格,這不是前:

var lines = richTextBox1.Text.Split('\n'); 
File.WriteAllLines(fileName, lines); 

然後我想:

var text = richTextBox1.Text; 
File.WriteAllText(fileName, text); 

這致函文件相同的文字與改變但它並沒有保留將文本作爲一行寫入文件的格式。

+0

爲了節省: 'richTextBox1.SaveFile(fileName);'加載:'richTextBox1.LoadFile(fileName);' – LarsTech

回答

0

你要替換 「\ n」 和 「\ r \ n」 個

var text = richTextBox1.Text; 
text = text.Replace("\n", "\r\n"); 
File.WriteAllText(fileName, text); 
0

嗯,是這裏的幾個選項,其中沒有涉及分裂文本。

注:所有下面的代碼是使用具有作爲一個字符串的文件路徑私有變量:使用Text

public partial class Form1 : Form 
{ 
    private const string filePath = @"f:\public\temp\temp.txt"; 

第一個是簡單地保存所有的文字(包括\r\n字符)財產,與File.ReadAllTextFile.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.ReadAllLinesFile.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類的內置SaveFileLoadFile方法。這種方法將元數據寫入文件,所以如果你在記事本中打開它,你會看到一些其他的字符,包括各種格式信息。正因爲如此,我加入了通話圍繞try/catchLoadFile,因爲它會引發和異常,如果該文件不具有正確的格式,我回落到加載它與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); 
} 
相關問題