TOC

The community is working on translating this tutorial into Hindi, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

File handling:

Manipulating files and directories

In the previous chapter, we looked into reading and writing text with simple files. We used the File class for this, but it does a lot more than just reading and writing. When combined with the Directory class, we can perform pretty much any filesystem operation, like renaming, moving, deleting and so on.

This chapter will provide numerous examples of doing just those things. The explanations will be limited, since the methods used are pretty simple and easy to use. You should be aware of two things: First of all, make sure that you import the System.IO namespace like this:

using System.IO;

Also, be aware that we are not doing any exception handling here. We will check that files and directories exist before using it, but there's no exception handling, so in case anything goes wrong, the application will crash. Exception handling is generally a good idea when doing IO operations. For more information, please read the exception handling chapter in this tutorial.

In all of the examples, we use simple file and directory names, which will have to exist in the same directory as the generated EXE file of your application. In the project settings you can see where your EXE file is generated to.

Deleting a file

if(File.Exists("test.txt"))
{
    File.Delete("test.txt");
    if(File.Exists("test.txt") == false)
Console.WriteLine("File deleted...");
}
else
    Console.WriteLine("File test.txt does not yet exist!");
Console.ReadKey();

Deleting a directory

if(Directory.Exists("testdir"))
{
    Directory.Delete("testdir");
    if(Directory.Exists("testdir") == false)
Console.WriteLine("Directory deleted...");
}
else
    Console.WriteLine("Directory testdir does not yet exist!");
Console.ReadKey();

If testdir is not empty, you will receive an exception. Why? Because this version of Delete() on the Directory class only works on empty directories. It's very easy to change though:

Directory.Delete("testdir", true);

The extra parameter makes sure that the Delete() method is recursive, meaning that it will traverse subdirectories and delete the files of it, before deleting the directories.

Renaming a file

if(File.Exists("test.txt"))
{
    Console.WriteLine("Please enter a new name for this file:");
    string newFilename = Console.ReadLine();
    if(newFilename != String.Empty)
    {
File.Move("test.txt", newFilename);
if(File.Exists(newFilename))
{
    Console.WriteLine("The file was renamed to " + newFilename);
    Console.ReadKey();
}
    }
}

You will notice that we use the Move() method to rename the file. Why not a Rename() method? Because there are no such method, since moving and renaming is essentially the same thing.

Renaming a directory

Doing the same thing with a directory is just as easy:

if(Directory.Exists("testdir"))
{
    Console.WriteLine("Please enter a new name for this directory:");
    string newDirName = Console.ReadLine();
    if(newDirName != String.Empty)
    {
Directory.Move("testdir", newDirName);
if(Directory.Exists(newDirName))
{
    Console.WriteLine("The directory was renamed to " + newDirName);
    Console.ReadKey();
}
    }
}

Creating a new directory

Creating a brand new directory is easy too - just use the CreateDirectory() method on the Directory class, like in this example:

Console.WriteLine("Please enter a name for the new directory:");
string newDirName = Console.ReadLine();
if(newDirName != String.Empty)
{
    Directory.CreateDirectory(newDirName);
    if(Directory.Exists(newDirName))
    {
Console.WriteLine("The directory was created!");
Console.ReadKey();
    }
}

Reading & Writing Files

As a final example, I will show you how the File class makes it very easy to read from and write to a file. This can be done in a whole lot of ways with C#, but the Read* and Write* methods, found on the File class, are probably the easiest ones to use. There are three versions: WriteAllBytes(), WriteAllLines() and WriteAllText(), with corresponding Read methods. The simplest one to use is the last one, which will take a simple string as its input. Let me illustrate how they work with a simple example:

string fileContents = "John Doe & Jane Doe sitting in a tree...";
File.WriteAllText("test.txt", fileContents);

string fileContentsFromFile = File.ReadAllText("test.txt");
Console.WriteLine(fileContentsFromFile);

Notice how few lines of code I need to write something to a file and then read it back! The first parameter to both methods is the path to where the text should be written to and read from. Normally, you would specify a full path here, but to make the example more clear, I only specify a filename, resulting in the file being written to the same directory as the EXE file.

Summary

As you can see, the File and Directory classes are a huge help when you need to work with files and directories. They can help you do most of the operations needed, and if you need to do even more advanced stuff, these classes and their methods will usually serve as great building blocks to expand on.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!