C-sharp provides a file class which is used in manipulating text files. the file class is within the system namespace. also we can use the streamreader and streamwriter classes, which are within the system. io, namespace for reading from and writing to a text file. in this article we'll see examples of creating a text file, reading contents of a text file and appending lines to a text file.
1. Creating a text file
For creating text file we use the createtext method of the file class. the createtext methods takes in the path of the file to be created as an argument. it creates a file in the specified path and returns a streamwriter object which can be used to write contents to the file.
Example
Public class fileclass
{
Public static void main ()
{
Writetofile ();
}
Static void writetofile ()
{
Streamwriter SW;
Sw = file. createtext ("C :\\ mytextfile.txt ");
Sw. writeline ("God is greatest of them all ");
Sw. writeline ("this is second line ");
Sw. Close ();
Console. writeline ("File Created sucacessfully ");
}
}
2. Reading contents of a text file
For reading the contents of a text file we use the opentext method of the file class. the opentext methods takes in the path of the file to be opened as an argument. it opens the specified file and returns a streamreader object which can be used to read the contents of the file.
Example
Public class fileclass
{
Public static void main ()
{
Readfromfile ("C: \ mytextfile.txt ");
}
Static void readfromfile (string filename)
{
Streamreader SR;
String S;
Sr = file. opentext (filename );
S = Sr. Readline ();
While (s! = NULL)
{
Console. writeline (s );
S = Sr. Readline ();
}
Sr. Close ();
}
}
3. appending content to a text file
For appending content to a text file we use the appendtext method of the file class. the appendtext methods takes in the path of the file to which the contents to be appended as an argument. it opens the file in the specified path and returns a streamwriter object which can be used to append contents to the file.
Example
public class fileclass
{
Public static void main ()
{< br> appendtofile ();
}< br> static void appendtofile ()
{< br> streamwriter SW;
Sw = file. appendtext ("C :\\ mytextfile.txt");
SW. writeline ("this line is appended");
SW. close ();
console. writeline ("text appended successfully");
}< br>