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.

By Tim TrottIntroduction to Programming with C# • February 16, 2009
Introduction to Programming with C#

This article is part of a series of articles. Please use the links below to navigate between the articles.

  1. Learn to Program in C# - Full Introduction to Programming Course
  2. Introdution to Programming - C# Programming Fundamentals
  3. Guide to C# Data Types, Variables and Object Casting
  4. C# Operators: Arithmetic, Comparison, Logical and more
  5. Application Flow Control and Control Structures in C#
  6. Introduction to Object Oriented Programming for Beginners
  7. Introduction to C# Object-Oriented Programming Part 2
  8. C# Collection Types (Array,List,Dictionary,HashTable and More)
  9. Error and Exception Handling in C#
  10. Events, Delegates and Extension Methods
  11. Complete Guide to File Handling in C# - Reading and Writing Files
  12. Introduction to XML and XmlDocument with C#
  13. What is LINQ? The .NET Language Integrated Query
  14. Introduction to Asynchronous Programming in C#
  15. Working with Databases using Entity Framework
  16. All About Reflection in C# To Read Metadata and Find Assemblies
  17. Debugging and Testing in C#
  18. Introduction to ASP.Net MVC Web Applications and C#
  19. Windows Application Development Using .Net and Windows Forms
  20. Assemblies and the Global Assembly Cache in C#
  21. Working with Resources Files, Culture & Regions in .Net
  22. The Ultimate Guide to Regular Expressions: Everything You Need to Know
Complete Guide to File Handling in C# - Reading and Writing Files

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.

C#
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.

C#
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.

C#
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.

C#
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);
  }
}
C#
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.

C#
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".

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
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);
  }
}

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.