Pratik Singhal
Pratik Singhal

Reputation: 6492

Why is the newline character not working?

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)

Upvotes: 2

Views: 17632

Answers (4)

RobertKing
RobertKing

Reputation: 1921

try

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

instead of

sw.Write("HelloWorld\n");

Upvotes: 1

Raghuveer
Raghuveer

Reputation: 2638

You can also try with

sw.WriteLine("HelloWorld");
sw.WriteLine("ByeWorld");

Upvotes: 2

Vnz Dichoso
Vnz Dichoso

Reputation: 182

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

Upvotes: 1

Rohit
Rohit

Reputation: 10236

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

Upvotes: 9

Related Questions