Reputation: 6492
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
Reputation: 1921
try
sw.Write("HelloWorld\\n");
instead of
sw.Write("HelloWorld\n");
Upvotes: 1
Reputation: 2638
You can also try with
sw.WriteLine("HelloWorld");
sw.WriteLine("ByeWorld");
Upvotes: 2
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