Friday, April 22, 2016

Create Text File using C#


This post shows a sample code in C# to create a text file. This code can also be used to create a log file for any console or windows form based application.

It is assumed that you already have basic knowledge about C#.

class Program
{
  static void Main(string[] args)
  {
    String fileName = @".\File.txt";
    TextWriter fileWriter = new StreamWriter(fileName, true);
    String fileText = "First Line";
    fileWriter .WriteLine(fileText );

    fileText   = "SecondLine";
    fileWriter .WriteLine(fileText);

    fileWriter .Close();
  }
}

Understanding the code - 

@".\File.txt";
\ in C# has a special meaning. It is used to define an escape sequence. But here we want to use it to represent directory path. So to tell the compiler to not to treat \ as part of escape sequnce we can either put an extra \ with existing \ or put @ before starting the string. 
Strings with @ are called as verbatim string 

Below two strings as same - 
@".\File.txt";
".\\File.txt";

(.) represents current directory which contains the executable. If it is executed from VSTS IDE, (.) represents bin directory.

So overall .\File.txt means text file is in same directory where executable is.

TextWriter fileWriter = new StreamWriter(fileName, true);
This creates a text file in hard disk and associates a default buffer to it.
FileName contains path, file name and extension.
True means if file already exists, append the new text.

string file Text   = "SecondLine";
fileWriter .WriteLine( fileText);
WriteLine method writes the content of string in buffer associated with the file.

fileWriter .Close();
Finally Close() methods writes all the contents of buffer to actual file, saves the file and releases the buffer.

Did you like the post. Please share your thoughts.

No comments:

Post a Comment