开发者

How do I save a multi-line textbox as one line to a text file?

Ok guys, I am making a function to save a file. I have come across a problem in that when I save the data from multi-line text boxes it saves x amount of lines as x amount of lines in the text file.

So for example if the user entered:

line one
line two
line three

it would show as:

line one
line two
line three

as I want it to display as:

line one \n line two \n line three \n

The code I have is:

                savefile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                savefile.Title = "Save your file";
                savefile.FileName = "";
                savefile.Filter = "ChemFile (*.cd)|*.cd|All Files|*.*";

                if (savefile.ShowDialog() != DialogResult.Cancel)
                {                    
                   // save the text file information
                    for (int i = 开发者_如何学编程0; i < noofcrit; i++)
                    {
                        cdfile[i] = crittextbs[i].Text;
                    }                    
                }
                    // Compile the file
                    SaveFile = savefile.FileName;
                    System.IO.File.WriteAllLines(SaveFile, cdfile);

Any ideas how I can save multiline text files as one line? Thanks.


Replace Newline character with @" \n "or" \\n ", using @ to ignore any escape char

   string s= yourTextBox.Text.Replace(Environment.NewLine, @" \n "));


I think you may need to do something like this. I'm not actually sure what the best way is to show escape characters. Also, I would use a StreamWriter.

string myData = txtMyTextBox.Text.Replace("\r"," \\r ").Replace("\n"," \\n ");
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
     sw.Write(myData);
}


If you get the multi-line strings in a string array, you could just join them into a single line:

string[] multiline = new []{"multi","line","text"};
string singleLine = string.Join(@"\n",multiline);

if it's all a single line, a simple Replace would do the trick,

string singleLine = multiline.Replace("\r",string.Empty).Replace("\n",@"\n");


It's all one line really ;)

Multi-line text boxes depending on platform (Win32 here) will save as:

Line\r\n Line\r\n Line\r\n

So you just need to replace \r\n with \n or whatever character replacement you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜