• home
  • Email: trainings@synapseindia.careers



An Easiest way for File Handling in C#

Mar 17, 2016

File Handling is quite easy in C# in comparison of Working with other languages like C++ and Java. .NET provides various classes for handling file operations like Creating File, Deleting File as well as reading and writing data into it. In this article we will use FileStream, StreamReader and StreamWriter Classes for performing these operations. See the code below, where we have 3 methods name accept, read and write for accepting file path, reading data and writing data into it.

using System;
using System.IO;
class myclass
static string path = null;
public static void accept()
Console.WriteLine("Give the path ");
path = Console.ReadLine();

public static void read()
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string data = null;
Console.WriteLine("REading all line s by File Stream :");
while ((data = sr.ReadLine()) != null)


Console.WriteLine("Reading all lines by using File class");
string[] lines = File.ReadAllLines(path);
foreach (string l in lines)
public static void write()
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("What to writ e");
string data = Console.ReadLine();
Console.WriteLine("Data writtened");

public static void Main()
Console.WriteLine("Accepting path ");
Console.WriteLine("Writin data ");
Console.WriteLine("Reading data ");


FileStream works with both classes "StreamWriter" and "StreamReader". FileStream passes certain parameters to its constructor like path and certain details for opening and starting read operation on provided file in path. And then after it's instance is provided to the constructor of StreamReader class and StreamWriter class. Try with this example and perform your file handling easily.

SynapseIndia has been working on various projects of .NET including many of ASP.NET. ASP.NET is considered to be perfect for Rapid Application Development and therefore it is one of the perfect technology in SynapseIndia Technologies.

SynapseIndia (CEO: Shamit Khemka)