I have the following code:
void AppendText(string txt)
{
txt = txt + "\r\n";
Textbox1.AppendText(txt);
Textbox1.Select(Textbox1.Text.Length,0);
}
//....
void someFunction()
{
//...
string log = @"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
开发者_如何学Cusing (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(Textbox1.Text);
}
}
//...
}
The problem is in Textbox1.Text field in the form, "\r\n" works fine, but when I copy the Textbox1.Text to log.txt, the log.txt doesn't have new line where it's supposed to be. Instead there's a strange charater like this "[]" where "\r\n" is. I think problem lies in the sw.Write(tbox.text) right? But I don't know how to fix it. Could anyone give me a hand? Help is really appreciated. Thanks in advance.
My guess would be that the Textbox creates unicode characters (two bytes per character). In what format are you reading the data? ASCII unicode UTF?
If I remember correctly /n/r is an old trick to write a newline character to the string but in what format and what does it mean? Environment.Newline is much better and would work on windows mobile/unix builds too.
I usually create a class level variable called br with environment.newline as its content, creates much shorter code.
You should do like this.
string log = @"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach(string line in Textbox1.Lines)
sw.Write(line+sw.NewLine);
}
}
Your code is correct. Just add sw.Close();
after sw.Write(Textbox1.Text);
精彩评论