Complete Guide to File Handling in C# - Reading and Writing Files How to work with File Handling in C# and how we can use the System.IO.File class to perform some basic and complex file operations.
This article is part of a series of articles. Please use the links below to navigate between the articles.
- Learn to Program in C# - Full Introduction to Programming Course
- Introdution to Programming - C# Programming Fundamentals
- Guide to C# Data Types, Variables and Object Casting
- C# Operators: Arithmetic, Comparison, Logical and more
- Application Flow Control and Control Structures in C#
- Introduction to Object Oriented Programming for Beginners
- Introduction to C# Object-Oriented Programming Part 2
- C# Collection Types (Array,List,Dictionary,HashTable and More)
- Error and Exception Handling in C#
- Events, Delegates and Extension Methods
- Complete Guide to File Handling in C# - Reading and Writing Files
- Introduction to XML and XmlDocument with C#
- What is LINQ? The .NET Language Integrated Query
- Introduction to Asynchronous Programming in C#
- Working with Databases using Entity Framework
- All About Reflection in C# To Read Metadata and Find Assemblies
- Debugging and Testing in C#
- Introduction to ASP.Net MVC Web Applications and C#
- Windows Application Development Using .Net and Windows Forms
- Assemblies and the Global Assembly Cache in C#
- Working with Resources Files, Culture & Regions in .Net
- The Ultimate Guide to Regular Expressions: Everything You Need to Know

In this tutorial, we will look at reading and writing files in C#. The System.IO.File class comes with everything we need, making it very easy to read and write a file.
Reading and Writing Files
The first example we will look at reads the entire contents of a file and displays it on the screen.
if(File.Exists("test.txt"))
{
string content = File.ReadAllText("test.txt");
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
We can also use the WriteAllText method to save data to a text file.
string content = "Hello World!";
File.WriteAllText("test.txt", content);
This method will overwrite any existing file, so it will be lost if you already have contents. Instead, we can append data to an existing file, preserving the previous content.
string content = "Hello World!";
File.AppendAllText("test.txt", content);
We can also read and write text files line by line. Instead of working with strings, the methods work with string arrays.
if(File.Exists("test.txt"))
{
string[] content = File.ReadAllLines("test.txt");
Console.WriteLine("Current content of file:");
foreach (string line in content)
{
Console.WriteLine(line);
}
}
var content = new string[1] { "Hello World 1", "Hello World 2" };
File.WriteAllLines("test.txt", content);
We can also use streams to read and write files. Streams are a collection of abstract classes that can consistently provide information from various sources. We can use the same method to read data from a file stream as from a memory or network stream.
We are going to take advantage of the using()
statement of C#, which ensures that the file reference is closed once it goes out of scope. If you don't use the statement, you will have to call the Close() manually
method on the StreamWriter instance.
using (StreamReader file =
new StreamReader("test.txt"))
{
while((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
In this example, we prompt the user for an input and write each line to the file until the user enters "exit".
Console.WriteLine("Please enter some text. Type exit to end.");
using(StreamWriter sw = new StreamWriter("test.txt"))
{
string newContent = Console.ReadLine();
while(newContent != "exit")
{
sw.Write(newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
}
Copy, Move and Delete Files
The File class also has properties to copy, move and delete files.
File.Copy("test.txt", "test copy.txt");
File.Move("test.txt", "c:temptest.txt");
File.Delete("test.txt");
File Information
As well as reading and writing file contents, you can get a lot of additional information about a file using the FileInfo
class.
FileInfo fi = new FileInfo("c:\dev\test.txt");
if (fi != null)
{
long filesize = fi.Length;
DateTime lastModified = fi.LastWriteTimeUtc;
bool readOnly = fi.IsReadOnly;
}
You can get more information about a file, including the full path, extension, filename, and attributes.
Copy, Move and Delete Directories
A lot of the functions you can perform on files you can also perform on directories.
Directory.CreateDirectory(@"c:devtest");
Directory.Move(@"c:devtest", @"c:temptest");
if (Directory.Exists(@"c:temptest"))
Directory.Delete(@"c:temptest");
Directory Information
As with FileInfo, you can use Directory to get information about a directory.
DateTime created = Directory.GetCreationTimeUtc(@"c:devtest");
DirectoryInfo parent = Directory.GetParent(@"c:devtemptemp2");
string path = parent.FullName;
Directory Recursion
Directory recursion is a technique to get all the files and directories below the specified directory. It can be used to get a full folder list and include all files in the specified directory and all the subdirectories.
static void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
{
Console.WriteLine(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}