Skip to main content

How to write to a Text File using C#

In this article we will see how to write text in txt file using C#.
In our dot-net application frequently we required to either read from text file or write to text file. We will see how to read from txt file later.
Here we will focus on writing into text file.

The main class file we are going to user for either reading or writing is “System.IO.File” class.

File class contains a various methods to write in a txt file.

To write all the text in a file see the below example

Example For WriteAllText

// WriteAllText method will creates a new file with given name in path,
// Writes the given string to a file,
// and then close the file.
// It is not required to eithe call Close() or Flush() method.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
string textToWrite = "Here write those text or paragraph which you want to add into text file. You can write as many characters as you want.";

File.WriteAllText(filePath, textToWrite);
}
}

Now you can also write the list of lines into a text file. See below example for more detail and syntax.

Example For WriteAllLines

// WriteAllText method will creates a new file with given name in path,
// writes a collection of strings to the file,
// and then close the file.
// It is not required to eithe call Close() or Flush() method.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
string[] linesToWrite = { "Text of first line to write into the notepad",
"Text of second line to write into the notepad",
"Text of third line to write into the notepad"
};

File.WriteAllLines(filePath, linesToWrite);
}
}

Above both example code are creating a new file or over right an existing file.

Now lets see how to append some text to an existing file. To append the text to existing file here we will use StreamWriter class from System.IO namespace.

Example For WriteLine

// Here we will use using statement, which will call flushes and closes the stream. It will also calls the dispose on the stream object itself.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
using (StreamWriter fileToAppend = new StreamWriter(filePath, true))
{
fileToAppend.WriteLine("Text of fourth line to write into the notepad");
}
}
}

Notes:
In below cases you may get an exceptions
– File is exists at given path but read only.
– If disk is full
– If path name is too long etc

You can download an example here

Introduction to Class in OOPS with C#.net

Understanding class

A class is like a blueprint. It allows us to create our own custom data types by grouping methods, events and variables of different types like int, string or any other custom types. Class defines the data and behavior of a type.

A class can be defined with a keyword “class” followed by the class name and body of the class with a pair of curly braces.
Let’s have a look at the general form of a class body.

below is the general form of a class body.

//Public is the access specifier while Calculator is the name of the class
public class Calculator
{
//variables declaration
private int var1;
private int var2;

//methods declaration
public decimal Add(decimal val1, decimal val2)
{
return val1+val2;
}
}

Classes supports inheritance while structs can’t support it.
Access specifiers plays an important role in the class definition, which specify the rules for accessing the member as well as the class itself. Default access specifier for the class is internal while for member it is private.

Data type specifies the type of variable, and return type specifies the data type of the data the method returns.

To access the class members we need to create an object of the class if class is not static, and using object name(dot)membername or member function name

See the below code for accessing Add method of Calculator class

Calculator calc = new Calculator();
decimal finalSum = calc.Add(10,20);