用C#编写Unix样式的文本文件 [英] Writing Unix style text file in C#

查看:153
本文介绍了用C#编写Unix样式的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#程序以Unix风格的换行符编写文本文件.

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!");

这也不是:

TextWriter fileTW = ...

fileTW.Write("Hello World! + \n");

在两种情况下,'\ n'都被替换为'\ r \ n',这是我不想要的!我一直在用十六进制编辑器进行验证,该编辑器显示每行以0x0D0A结尾.

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.

有什么想法吗?

谢谢!

对不起大家,虚惊一场!

Sorry everyone, false alarm!

让我解释一下...

我的TextWriter正在写入MemoryStream,然后使用SharpZLib将其添加到tar存档中.事实证明,通过使用WinZIP提取文本文件,它会将\ n的每个实例替换为\ r \ n.如果我将同一个tar存档复制到我的Ubuntu机器上并解压缩到那里,则只有\ n在那里.奇怪!

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!

推荐答案

我无法重现此内容.示例代码:

I'm unable to reproduce this. Sample code:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        using (TextWriter fileTW = new StreamWriter("test.txt"))
        {
            fileTW.NewLine = "\n";            
            fileTW.WriteLine("Hello");
        }
    }
}

之后:

c:\users\jon\Test>dir test.txt
 Volume in drive C has no label.
 Volume Serial Number is 4062-9385

 Directory of c:\users\jon\Test

20/10/2011  21:24                 6 test.txt
               1 File(s)              6 bytes

请注意大小-6个字节-"Hello"为5,"\ n"为一个.在未设置NewLine属性的情况下,该值为7("\ r \ n"为两个).

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").

您能提出一个类似的简短但完整的程序来说明问题吗?您如何确定文件之后是否包含"\ 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?

这篇关于用C#编写Unix样式的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆