Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

newline - Writing Unix style text file in C#

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 = "
";

fileTW.WriteLine("Hello World!");

Neither does this:

TextWriter fileTW = ...

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

In both cases the ' ' is being replaced with ' ', 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 with . If I copy the same tar archive to my Ubuntu machine and extract there, only the is there. Weird!

Sorry if I wasted anyone's time! Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = "
";            
            fileTW.WriteLine("Hello");
        }
    }
}

Afterwards:

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

 Directory of c:usersjonTest

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

Note the size - 6 bytes - that's 5 for "Hello" and one for the " ". Without setting the NewLine property, it's 7 (two for " ").

Can you come up with a similar short but complete program demonstrating the problem? How are you determining that your file contains " " afterwards?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...