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.

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. Introduction to Object Oriented Programming for Beginners
  4. Introduction to C# Object-Oriented Programming Part 2
  5. Application Flow Control and Control Structures in C#
  6. Guide to C# Data Types, Variables and Object Casting
  7. C# Collection Types (Array,List,Dictionary,HashTable and More)
  8. C# Operators: Arithmetic, Comparison, Logical and more
  9. Using Entity Framework & ADO.Net Data in C# 7
  10. What is LINQ? The .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. All About Reflection in C# To Read Metadata and Find Assemblies
  14. What Are ASP.Net WebForms
  15. Introduction to ASP.Net MVC Web Applications and C#
  16. Windows Application Development Using .Net and Windows Forms
  17. Assemblies and the Global Assembly Cache in C#
  18. Working with Resources Files, Culture & Regions in .Net
  19. The Ultimate Guide to Regular Expressions: Everything You Need to Know
  20. Introduction to XML and XmlDocument with C#
  21. Complete Guide to File Handling in C# - Reading and Writing Files

In this tutorial, we are going to have a look at reading and writing files in C#. The System.IO.File class comes with everything we need, making it very easy to do simple reading and writing of a file.

Reading and Writing Files

The first example we are going to look at simply 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 if you already have contents it will be lost. 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 which can provide information from a variety of sources in a consistent manner. We can use the same method to read data from a file stream as we do from a memory stream or a 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 using statement, you will have to manually call the Close() 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 which you can use 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 a lot more information about a file, including the full path, extension, filename and its 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 used 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);
  }
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

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?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.