Basics of File Handling in C#

Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for writing and reading. A stream is a sequence of bytes which is used for communication. Two stream can be formed from file one is input stream which is used to read the file and another is output stream is used to write in the file. In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure.

File-Handling-Class-Hierarchy

Here we are going to discuss about two classes which are useful for writing in and reading from the text file.

StreamWriter Class

The StreamWriter class implements TextWriter for writing character to stream in a particular format. The class contains the following method which are mostly used.



Method Description
Close() Closes the current StreamWriter object and stream associate with it.
Flush() Clears all the data from the buffer and write it in the stream associate with it.
Write() Write data to the stream. It has different overloads for different data types to write in stream.
WriteLine() It is same as Write() but it adds the newline character at the end of the data.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to write user input 
// to a file using StreamWriter Class
using System;
using System.IO;
  
namespace GeeksforGeeks {
      
class GFG {
      
    class WriteToFile {
          
        public void Data()
        {
            // This will create a file named sample.txt
            // at the specified location 
            StreamWriter sw = new StreamWriter("H://geeksforgeeks.txt");
              
            // To write on the console screen
            Console.WriteLine("Enter the Text that you want to write on File"); 
              
            // To read the input from the user
            string str = Console.ReadLine(); 
              
            // To write a line in buffer
            sw.WriteLine(str); 
              
            // To write in output stream
            sw.Flush(); 
              
            // To close the stream
            sw.Close(); 
        }
    }
      
    // Main Method
    static void Main(string[] args)
    {
        WriteToFile wr = new WriteToFile();
        wr.Data();
        Console.ReadKey();
    }
}
}

chevron_right


Input:

Output: You will find the file at the specified location having the content:

StreamReader Class

The StreamReader class implements TextReader for reading character from the stream in a particular format. The class contains the following method which are mostly used.

Method Description
Close() Closes the current StreamReader object and stream associate with it.
Peek() Returns the next available character but does not consume it.
Read() Reads the next character in input stream and increment characters position by one in the stream
ReadLine() Reads a line from the input stream and return the data in form of string
Seek() It is use to read/write at the specific location from a file

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to read from a file
// using StreamReader Class
using System;
using System.IO;
  
namespace GeeksforGeeks {
      
class GFG {
      
    class ReadFile {
          
        public void DataReading()
        {
            // Takinga a new input stream i.e. 
            // geeksforgeeks.txt and opens it
            StreamReader sr = new StreamReader("H://geeksforgeeks.txt");
              
            Console.WriteLine("Content of the File"); 
              
            // This is use to specify from where 
            // to start reading input stream
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
              
            // To read line from input stream
            string str = sr.ReadLine(); 
              
            // To read the whole file line by line
            while (str != null
            {
                Console.WriteLine(str);
                str = sr.ReadLine();
            }
            Console.ReadLine(); 
              
            // to close the stream
            sr.Close(); 
        }
    }
      
    // Main Method
    static void Main(string[] args)
    {
        ReadFile wr = new ReadFile();
        wr.DataReading();
    }
}
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Competitive Programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.