Learning never exhausts the mind

Published on by

In this tutorials, 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.
Introduction to Programming with C# Series
  1. Introduction to Programming with C# 7
  2. C# Programming Fundamentals
  3. Introduction to Object-Oriented Programming
  4. C# Object-Oriented Programming Part 2
  5. Flow Control and Control Structures in C#
  6. C# Data Types, Variables and Casting
  7. C# Collection Types (Array, List, Dictionary, Hash Table)
  8. C# Operators: Arithmetic, Comparison, Logical and more
  9. Using Data in C# 7 with ADO.Net & Entity Framework
  10. LINQ: .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. Reflection in C#
  14. What Are ASP.Net Webforms
  15. Introduction to ASP.Net MVC
  16. Windows Application Development
  17. Assemblies and the Global Assembly Cache in C#
  18. Working with Resources Files, Culture & Regions
  19. Regular Expressions in C#
  20. Introduction to XML with C#
  21. Complete Guide to File Handling in C#

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.

  string content = File.ReadAllText("test.txt");
  Console.WriteLine("Current content of file:");

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 if you already have contents it will be lost. 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 to text files line by line. Instead of working with strings, the methods work with string arrays.

  string[] content = File.ReadAllLines("test.txt");
  Console.WriteLine("Current content of file:");
  foreach (string line in content)
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 to 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.

using (StreamReader file =   
    new StreamReader("test.txt"))
  while((line = file.ReadLine()) != null)  

In this example, we prompt the user for an input and write each line to the file until the users 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 which you can use for copy, move and delete files.

File.Copy("test.txt", "test copy.txt");
File.Move("test.txt", "c:temptest.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 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.

Directory.Move(@"c:devtest", @"c:temptest");

if (Directory.Exists(@"c:temptest"))

Directory Information

As with FileInfo, you can use Directory to get infomrtaion 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 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 in all the subdirectories.

static void DirSearch(string sDir)
    foreach (string d in Directory.GetDirectories(sDir))
      foreach (string f in Directory.GetFiles(d))
  catch (System.Exception excpt)
Tutorial Series

This post is part of the series Introduction to Programming with C#. Use the links below to advance to the next tutorial in the couse, or go back and see the previous in the tutorial series.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.