Web Design that taps into the haromny and vision of your dreams.

Complete Guide to File Handling in C#

By on in Coding

662 words, estimated reading time 4 minutes.

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

In this tutorials, we are going to have a look at reading and writing files with 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.

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

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 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)  
  {  
    Console.WriteLine(line);  
  }
}

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:\temp\test.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 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.CreateDirectory(@"c:\dev\test");
Directory.Move(@"c:\dev\test", @"c:\temp\test");
 
if (Directory.Exists(@"c:\temp\test"))
    Directory.Delete(@"c:\temp\test");

Directory Information

As with FileInfo, you can use Directory to get infomrtaion about a directory.

DateTime created = Directory.GetCreationTimeUtc(@"c:\dev\test");
DirectoryInfo parent = Directory.GetParent(@"c:\dev\temp\temp2");
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)
{
  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);
  }
}

Last updated on: Thursday 11th October 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.