c# 将 textbox.text 保存到 txt 文件。 txt 文件无法识别行尾字符
我有以下代码:
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))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(Textbox1.Text);
}
}
//...
}
问题出在表单中的 Textbox1.Text 字段中,“\r\n”工作正常,但是当我将 Textbox1.Text 复制到 log.txt 时,log.txt 没有新行它应该在哪里。相反,有一个奇怪的字符,例如“[]”,其中“\r\n”所在。我认为问题出在 sw.Write(tbox.text) 对吧?但我不知道如何解决它。有人可以帮我吗?非常感谢帮助。提前致谢。
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))
{
using (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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的猜测是文本框创建 unicode 字符(每个字符两个字节)。
您以什么格式读取数据? ASCII 统一码 UTF?
如果我没记错的话 /n/r 是一个向字符串写入换行符的老技巧,但是以什么格式以及它的含义是什么? Environment.Newline 更好,也可以在 windows mobile/unix 版本上工作。
我通常创建一个名为 br 的类级别变量,以environment.newline 作为其内容,创建更短的代码。
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.
你的代码是正确的。只需在
sw.Write(Textbox1.Text);
之后添加sw.Close();
Your code is correct. Just add
sw.Close();
aftersw.Write(Textbox1.Text);