From RichTextBox to text files, line after line

后端 未结 3 2054
小蘑菇
小蘑菇 2020-12-18 17:59

I have trouble with saving file from Richtextbox to text file.

My richtextbox looks like this;

ABC    ...
 SDE   ...
KLO    ...

Af

相关标签:
3条回答
  • 2020-12-18 18:10

    I know this question is pretty old but here is an alternate code for people who might run into this problem in the future

    File.WriteAllLines(saveFileDialog1.FileName, richTextBox1.Lines);

    0 讨论(0)
  • 2020-12-18 18:18
    if (saveFileDialog2.ShowDialog() == DialogResult.OK)
    {
        StreamWriter sw = File.CreateText(saveFileDialog2.FileName);
        foreach(String s in richTextBox1.Lines)
        {
            sw.WriteLine(s);
        }
        sw.Flush();
        sw.Close();
    }
    
    0 讨论(0)
  • 2020-12-18 18:29

    You are probably getting this because you are trying to save richTextBox1.Text (the whole text) in one line only using the following code

    StreamWriter sw = File.CreateText(saveFileDialog2.FileName);
    sw.WriteLine(richTextBox1.Text);
    sw.Flush();
    sw.Close();
    

    It's recommended to use sw.WriteLine() on a specific line number in richTextBox1 then move to another line.

    Example

    for (int i = 0; i < richTextBox1.Lines.Length; i++)
    {
        sw.WriteLine(richTextBox1.Lines[i]);
    }
    sw.Flush();
    sw.Close();
    

    Another Solution


    There's already a built-in function for RichTextBox to save a file with a specific encoding. You may use RichTextBox.SaveFile() for this purpose.

    Example

    RichTextBox.SaveFile(string path, RichTextBoxStreamType);
    

    Where path represents saveFileDialog2.FileName in your code. For RichTextBoxStreamType, it's best to set it as RichTextBoxStreamType.PlainText as long as you do not use RTF such as Color/Font/Protection/Indent/etc...

    Then, you may read the file again using the following method

    RichTextBox.LoadFile(string path, RichTextBoxStreamType);
    

    NOTICE: If the file is not in RTF and you try to read it in RTF (RichTextBox.LoadFile(string path, RichTextBoxStreamType.RichText);) you may encounter formatting errors. In this case, you'll need to catch the exception and read the file in a Plain or Unicode encoding.

    Example

    RichTextBox _RichTextBox = new RichTextBox();
    try
    {
         _RichTextBox.LoadFile(@"D:\Resources\text.txt", RichTextBoxStreamType.RichText);
    }
    catch (Exception EX)
    {
         if (EX.Message.ToLower().Contains("format is not valid"))
         {
              _RichTextBox.LoadFile(@"D:\Resources\text.txt", RichTextBoxStreamType.PlainText);
         }
    }
    

    Thanks,
    I hope you find this helpful :)

    0 讨论(0)
提交回复
热议问题