Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - From RichTextBox to text files, line after line

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

My richtextbox looks like this;

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

After i saved it looks like this:

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

But i want the same like richtextbox line after lines. What did i do wrong?

 if (saveFileDialog2.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = File.CreateText(saveFileDialog2.FileName);
            sw.WriteLine(richTextBox1.Text);
            sw.Flush();
            sw.Close();

            //File.WriteAllText(saveFileDialog2.FileName, str);
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:Resourcesext.txt", RichTextBoxStreamType.RichText);
}
catch (Exception EX)
{
     if (EX.Message.ToLower().Contains("format is not valid"))
     {
          _RichTextBox.LoadFile(@"D:Resourcesext.txt", RichTextBoxStreamType.PlainText);
     }
}

Thanks,
I hope you find this helpful :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...