Write textbox text to a file while keeping newlines

有些话、适合烂在心里 提交于 2019-12-25 02:17:10

问题


I have tried using: StreamWriter.WriteLine() StreamWriter.Write() File.WriteAllText()

But all of those methods write the textbox text to the file without keeping newlines and such chars. How can I go about doing this?

EDIT:

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog s = new SaveFileDialog();
        s.FileName = "new_doc.txt";
        s.Filter = "Text File | *.txt";
        if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            File.WriteAllText(s.FileName, richTextBox1.Text);
        }
    }

I am using a multiline RichTextBox to do this.


回答1:


Maybe this would help. Is from StreamWriter class documentation.

string[] str = String.Split(...);

// Write each directory name to a file. 
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
    foreach (DirectoryInfo dir in cDirs)
    {
        sw.WriteLine(dir.Name);

    }
}

The idea is to get the text from your textbox and then split it after \n char. The result will be an array of strings, each element containing one line.

Later edit:

The problem is that return carriage is missing. If you look with debugger at the code, you will see that your string has only \n at a new line instead of \r\n. If you put this line of code in you function, you will get the results you want:

string tbval = richTextBox1.Text;
tbval = tbval.Replace("\n", "\r\n");

There should be other solutions for this issue, looking better than this but this one has quick results.




回答2:


To expand on tzortzik's answer, if you use StreamWriter and simply access the RichTextBox's Lines property, it will do the work for you:

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog s = new SaveFileDialog();
        s.FileName = "new_doc.txt";
        s.Filter = "Text File | *.txt";
        if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            using (StreamWriter sw = new StreamWriter(s.FileName))
            {
                foreach (string line in richTextBox1.Lines)
                {
                    sw.WriteLine(line);
                }
            }
        }
    }


来源:https://stackoverflow.com/questions/22263609/write-textbox-text-to-a-file-while-keeping-newlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!