用 C# 编写 Unix 风格的文本文件
我正在尝试使用 C# 程序编写带有 Unix 风格换行符的文本文件。
由于某种原因,以下代码不起作用:
TextWriter fileTW = ...
fileTW.NewLine = "\n";
fileTW.WriteLine("Hello World!");
这也不起作用:
TextWriter fileTW = ...
fileTW.Write("Hello World! + \n");
在这两种情况下,“\n”都被替换为“\r\n”,这是我不想要的!我一直在使用十六进制编辑器验证这一点,该编辑器显示以 0x0D0A 结尾的每一行。
有什么想法吗?
谢谢!
编辑:
对不起大家,误报!
请允许我解释一下...
我的 TextWriter 正在写入 MemoryStream,然后使用 SharpZLib 将其添加到 tar 存档中。事实证明,通过使用 WinZIP 提取文本文件,它用 \r\n 替换了 \n 的每个实例。如果我将相同的 tar 存档复制到我的 Ubuntu 计算机并在那里解压,则只有 \n 存在。诡异的!
抱歉,如果我浪费了任何人的时间!谢谢!
I'm trying to write a text file with Unix-style newlines with my C# program.
For some reason the following code doesn't work:
TextWriter fileTW = ...
fileTW.NewLine = "\n";
fileTW.WriteLine("Hello World!");
Neither does this:
TextWriter fileTW = ...
fileTW.Write("Hello World! + \n");
In both cases the '\n' is being replaced with '\r\n', which I don't want! I've been verifying this with a hex editor, which shows each line ending in 0x0D0A.
Any ideas?
Thanks!
EDIT:
Sorry everyone, false alarm!
Allow me to explain...
My TextWriter was writing to a MemoryStream, which was then being added to a tar archive using SharpZLib. It turns out that by extracting the text file using WinZIP, it was replacing every instance of \n with \r\n. If I copy the same tar archive to my Ubuntu machine and extract there, only the \n is there. Weird!
Sorry if I wasted anyone's time! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法重现这个。示例代码:
之后:
注意大小 - 6 字节 - 5 表示“Hello”,1 表示“\n”。如果不设置
NewLine
属性,则为 7(两个表示“\r\n”)。你能想出一个类似的简短但完整的程序来证明这个问题吗?您如何确定您的文件之后包含“\r\n”?
I'm unable to reproduce this. Sample code:
Afterwards:
Note the size - 6 bytes - that's 5 for "Hello" and one for the "\n". Without setting the
NewLine
property, it's 7 (two for "\r\n").Can you come up with a similar short but complete program demonstrating the problem? How are you determining that your file contains "\r\n" afterwards?
我和乔恩·斯基特处境相同。这是我对 MemoryStream 的测试,确认它确实使用您提供的 NewLine 值。
请随意修改其中之一并根据您的情况更新您的答案。
I'm in the same boat as Jon Skeet. Here's my tests against a MemoryStream that confirm it does use what you give it as the NewLine value.
Feel free modify one of these and update your answer with your scenario.