3

write the contents of person in a file

FirstName: Abcd

SecondName: Tsfsdfs

For this I wrote a sample application

namespace BinaryStream
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter binWriter = new StreamWriter(@"c:\happybirthday.txt");
            string name = "Sachin";
            string secondname = "tendulkar";
            string wishes = "happy birthday";

            string firstname = string.Format("FirstName: {0} \n", name);
            binWriter.Write(firstname);
            string sn = string.Format("SecondName: {0} \n", secondname);
            binWriter.Write(sn);
            binWriter.Close();          
        }
    }
}

IF I open the contents in the notepad, the strings are not displayed in the next line What is the reason for this? Is the format part is correct?

Ren
  • 1,111
  • 5
  • 15
  • 24
Raghav55
  • 3,055
  • 6
  • 28
  • 38

5 Answers5

6

You need to use WriteLine, not Write. Write does not put a linefeed\cr at the end of the line. Placing \n in the text only places a linefeed, and does not place a cariage return.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
3

You require both a carriage return and a line feed. You only have a line feed. Replace your \n with \r\n and you'll see it correctly in notepad.

pdriegen
  • 2,019
  • 1
  • 13
  • 19
1

You may find that you need a combination of a Carriage Return (CR) and a Line Feed (LF) character, not just the LF.

So - in your code, replace the \n with \r\n

Chris Roberts
  • 18,622
  • 12
  • 60
  • 67
1

For starters, you are creating a binary file rather than a text file. This is probably confusing Notepad.

Besides in C# the \n means LF only, you must use \r\n (CR - LF).

Just write this:

string[] lines = {"FirstName: Abcd", "SecondName: Tsfsdfs"};
System.IO.File.WriteAllLines(@"c:\happybirthday.txt", lines);
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • This isn't a C# thing, it has to do with the program reading the file. Notepad requires \r\n, winword deals with \n or \r\n just fine, as do many other programs. – Servy Apr 24 '12 at 15:08
0

New line is \n\r in windows. But some programs are intelligent enough to understand just \n. Others, like notepad - are not.

J0HN
  • 26,063
  • 5
  • 54
  • 85