2

I am new to C# file handling, and I am making a very simple program. The code is as follows:

class MainClass 
{
    public static void Main()
    {
        var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
        sw.Write("HelloWorld" +Environment.NewLine);
        sw.Write("ByeWorld");
        sw.Close(); 

        Console.ReadLine();
    }
}

The above code produces the following expected result in the text file:

HelloWorld
ByeWorld

I also wrote somewhat modified version of the code like this:

class MainClass 
{
    public static void Main()
    {
        var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
        sw.Write("HelloWorld\n");
        sw.Write("ByeWorld");
        sw.Close(); 

        Console.ReadLine();
    }
}

Here instead of using the

Environment.Newline

I directly added "\n" to the "HelloWorld" line. This produced the following output (int the text file):

HelloWorldByeWorld

My question is that why is the second piece of code not working? (Not producing the newline in the text file)

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97
  • 1
    Translating C# to Natural Language: Because `\n` does not get interpreted as *New Line Feed* in your working Environment :) – Alireza Oct 25 '13 at 05:34
  • 9
    It is `\r\n` on Windows. – Uwe Keim Oct 25 '13 at 05:35
  • 3
    I'm taking a guess here: You're looking at the result with Notepad. Notepad will not interpret a lone U+000A as a line break, only U+000D, U+000A, therefore what you wrote to the file *is* there, but you don't see it as such. At least not in Notepad. In any decent text editor you would. – Joey Oct 25 '13 at 05:43

4 Answers4

9

please try

  StreamWriter sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
    sw.Write("HelloWorld \r\n");
    sw.Write("ByeWorld");
    sw.Close(); 
    Console.ReadLine();

you can read it over here

Rohit
  • 10,056
  • 7
  • 50
  • 82
2

You can also try with

sw.WriteLine("HelloWorld");
sw.WriteLine("ByeWorld");
Raghuveer
  • 2,630
  • 3
  • 29
  • 59
1

change it to 'sw.WriteLine'. Like c++, it invoke newline. You could also read this: Create a .txt file if doesn't exist, and if it does append a new line

Community
  • 1
  • 1
Vnz Dichoso
  • 182
  • 1
  • 2
  • 11
1

try

sw.Write("HelloWorld\\n");

instead of

sw.Write("HelloWorld\n");
RobertKing
  • 1,853
  • 8
  • 30
  • 54