2017-10-20 105 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); 
} 
相关问题