0% found this document useful (0 votes)
60 views

Simple Text File Operation in C#

This document discusses basic text file operations in C#, including creating a text file using the File.CreateText method, reading from a text file using the File.OpenText method, and appending lines to a text file. The File and StreamReader/StreamWriter classes in the System.IO namespace provide methods for working with text files, allowing creation, reading, and writing of file contents in C#.

Uploaded by

akhan10200
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Simple Text File Operation in C#

This document discusses basic text file operations in C#, including creating a text file using the File.CreateText method, reading from a text file using the File.OpenText method, and appending lines to a text file. The File and StreamReader/StreamWriter classes in the System.IO namespace provide methods for working with text files, allowing creation, reading, and writing of file contents in C#.

Uploaded by

akhan10200
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Simple Text File Operations in C#.

0 Comments by Linda Karlsson 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 well 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 FileClass. 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(); } }

You might also like