Working with Files and Directories in .NET

.NET Core offers strong support for working with files and directories. You can take advantage of the Directory, DirectoryInfo, File, and FileInfo classes in.NET Core to work with directories and files. This article talks about how we can work with files and directories in .NET Core.

What is a File System?

A file system refers to the structure, rules, and regulations that are defined by the host Operating System of your computer that determines how the files and directories in your computer are arranged.

What are Files and Directories?

A directory is a name given to a special type of file that can be used to store other files and directories. The files and directories you create are usually stored in the permanent storage device in your computer. The System.IO namespace in .NET 6 comprises a collection of types (i.e., classes, structs, enums, and delegates) that enable reading and writing to files and data streams, as well as types that provide support for basic file and directory operations. You can take advantage of them to perform various operations, such as creating, reading, writing, and deleting files and directories.

Working with Directories in .NET

The Directory class contains static methods that you can use to create, copy, move, and delete directories.

Create a Directory in C#

The following code snippet illustrates how you can create a directory using the CreateDirectory static method of the Directory class. Note how the Exists static method of the Directory class has been used to check if a directory in the same name already exists in the path specified.

string path = @"D:\Workarea\Test";
if (!Directory.Exists(path))
{
   Directory.CreateDirectory(path);
}

You can create a subdirectory under a specified directory using the CreateSubDirectory method of the DirectoryInfo class. Here is how you can do this:

string path = @"D:\Workarea\Test";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
try 
{
	directoryInfo.CreateSubdirectory("SubDirectory");
}
catch(IOException ex) 
{
	Console.WriteLine(ex.Message);
}

Read: Working with Loops in C#

Move a Directory with the Directory.Move Method

You can use the Directory.Move method to move a directory as shown in the code snippet given below:

            string source = @"D:\Workarea\Test\Code";
            string destination = @"D:\Workarea\Test\NewDirectory";

            try
            {
                // First, you should ensure that the
                // source directory exists
                if (Directory.Exists(source))
                {
                    // You should eEnsure the destination
                    // directory doesn't already exist
                    if (!Directory.Exists(destination))
                    {
                        // Move the source directory
                        // to the new location
                        Directory.Move(source, destination);
                    }
                    else
                    {
                        Console.WriteLine("Destination directory" +
                                    " already exists...");
                    }
                }
                else
                {
                    Console.WriteLine("Source directory " +
                            "does not exist...");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

Delete a Directory in .NET and C#

To delete an existing directory, you can use the following piece of code:

string path = @"D:\Workarea\Test";
Directory.Delete(path);

Retrieve the Names of All Files and Directories in C#

The following code snippet illustrates how you can retrieve the names of all files and directories inside a specified directory.

using System;
using System.IO;
namespace FileIODemo {
  internal class Program {
    static void Main(string[] args) {
      string path = @ "D:\Workarea\Test";
      string[] files = Directory.GetFiles(path);
      string[] directories = 
      Directory.GetDirectories(path);

      Console.WriteLine("Displaying names of " +
        "files inside {0}\n", path);
      foreach(string file in files) {
        string fileNameWithoutExtension =
          Path.GetFileNameWithoutExtension(file);
        Console.WriteLine(fileNameWithoutExtension);
      }

      Console.WriteLine("\n\nDisplaying names of " +
        "directories inside {0}\n", path);
      foreach(string directory in directories) {
        string directoryName = new DirectoryInfo(
          Path.GetDirectoryName(directory)).Name;
        Console.WriteLine(directoryName);
      }
      Console.Read();
    }
  }
}

Note how the Path.GetFileNameWithoutExtension method has been called to truncate the file extension from the file name. Likewise, the DirectoryInfo class has been used to retrieve the name of the directory without the path.

Read: Tips for Writing Clean C# Code

How to Work with Files in .NET and C#

Like with the Directory and DirectoryInfo classes, you can take advantage of File and FileInfo classes to work with files in C#.

Update File Metadata with C#

The following code snippet illustrates how you can update the creation time, last access time, and last write time of a file in C#. It also sets the file as read-only.

string fileName = @"D:\Workarea\Test\abc.txt";
if (File.Exists(fileName))
{
   File.SetCreationTime(fileName, DateTime.Now);
   File.SetLastAccessTime(fileName, DateTime.Now);
   File.SetLastWriteTime(fileName, DateTime.Now);
   File.SetAttributes(fileName, FileAttributes.ReadOnly);
}

Retrieve File Metadata

You can take advantage of the FileInfo class to retrieve file metadata in C#. The following code snippet illustrates how this can be achieved:

string path = @ "D:\Workarea\Test";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
FileInfo[] files = directoryInfo.GetFiles("*.*");
foreach(FileInfo fileInfo in files) {
  Console.WriteLine("File Name : {0}", fileInfo.Name);
  Console.WriteLine("Length : {0}", fileInfo.Length);
  Console.WriteLine("Creation time : {0}", fileInfo.CreationTime);
  Console.WriteLine("Attributes : {0}", fileInfo.Attributes.ToString());
}

When you execute the above code, the file metadata would be displayed at the console as shown in Figure 1:

Working with Files and Directories in C#

You can create a file in several ways:

  • Using the File.Create method
  • Using the File.CreateText method
  • Using the FileInfo.Create method
  • Using the FileInfo.CreateText method

Read: Working with Strings in C#

How to Create a File with the C# Create Method

You can create a new file using the Create method of the FileInfo class as shown in the code snippet given below:

string path = @"D:\Workarea\Test\NewFile.txt";
try {
	FileInfo fileInfo = new FileInfo(path);
	using(FileStream fileStream = fileInfo.Create()) {
		Console.WriteLine("Creation Time: {0}", fileInfo.CreationTime);
		Console.WriteLine("Full Name: {0}", fileInfo.FullName);
		Console.WriteLine("File Attributes: {0}", fileInfo.Attributes.ToString());
		fileStream.Close();
		fileInfo.Delete();
	}
}
catch(Exception ex) {
	Console.WriteLine(ex.Message);
}

Note how the file stream has been closed before the file is deleted using the Delete method of the FileInfo class.

When you run the above program, here’s how the output would look like at the console window:

C# File and Directory tutorial

The following code snippet illustrates how you can create a file using the File class in C#:

 
string path = @"D:\Workarea\Test\NewFile.txt";
FileStream fileStream = File.Create(path);

Note that the File.Create method overwrites a file if it already exists, else it creates a new file at the location specified.

Check if a File Exists at a Specified Location

To check whether a file exists at a specified location you can use the following code:

bool isFileAvailable = File.Exists(@"D:\Test.txt");

Write Text to a File

The following code snippet checks if a file already exists in the specified path. If it doesn’t exist, it creates a new file and then uses a StreamWriter to write text to the file.

string path = @"D:\Workarea\Test\NewFile.txt";
if (!File.Exists(path)) {
	using(StreamWriter streamWriter = File.CreateText(path)) {
		streamWriter.WriteLine("Hello World!");
	}
}

Alternatively, you can take advantage of the File.WriteAllText method to write text to a file as shown in the following code:

File.WriteAllText(@"D:\Workarea\Test\NewFile.txt", "Hello World!");

The File.WriteAllText method creates a new file, writes the text to the file, and then closes the file. If the file already exists, it overwrites the file.

Read: Work with C# Math Operators

Append Text to a File

The following C# code shows how to append text to a file:

File.AppendAllText(@"D:\Workarea\Test\NewFile.txt", "Hello World!");

The AppendAllText method opens a file if it exists, appends a string to the file, and then closes the file. If the file doesn’t exist, it creates a new file, appends the text, and then closes the file.

Move a File

To move a file from the current location to a new location, you can use the File.Move method as shown in the C# code snippet given below:

File.Move(@"D:\Test.txt", @"E:\Test.txt");

Delete a File

To delete a file, you can take advantage of the File.Delete method as illustrated in the code snippet given below:

File.Delete(@"D:\Test.txt");

Summary of Working with Files in C#

Remember that the logged-in user or the user running the application must have the necessary permissions for working with files and directories on your computer. If you don’t have the necessary permission, you may not be able to create, edit or delete files and directories. In this article, we’ve discussed how we can work with files and directories in C#.

More by Author

Must Read