简体   繁体   English

c#将textbox.text保存为txt文件。 txt文件无法识别行尾字符

[英]c# saving textbox.text to txt file. txt file doesn't recognize end of line character

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. 问题出在形式为“ \\ r \\ n”的Textbox1.Text字段中,但是我将Textbox1.Text复制到log.txt时,log.txt的行没有新行。 Instead there's a strange charater like this "[]" where "\\r\\n" is. 而是有一个像“ []”这样的奇怪字符,其中“ \\ r \\ n”是。 I think problem lies in the sw.Write(tbox.text) right? 我认为问题出在sw.Write(tbox.text)对吗? 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). 我的猜测是,文本框会创建Unicode字符(每个字符两个字节)。 In what format are you reading the data? 您以什么格式读取数据? ASCII unicode UTF? 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? 如果我没记错的话,/ n / r是在字符串中写入换行符的旧技巧,但是格式是什么,这意味着什么? Environment.Newline is much better and would work on windows mobile/unix builds too. Environment.Newline更好,并且也可以在Windows Mobile / unix构建中使用。

I usually create a class level variable called br with environment.newline as its content, creates much shorter code. 我通常会创建一个名为br的类级别变量,其环境为environment.newline,创建的代码要短得多。

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(); 只需添加sw.Close(); after sw.Write(Textbox1.Text); sw.Write(Textbox1.Text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM