Ebooks

C# Directory tutorial

C# Directory tutorial shows how to work with directories in C#. In our examples we create directories, delete them, list directories or get their permissions.

Directory definition

A directory, also called a folder, is a location for storing files on your computer. In addition to files, a directory also stores other directories or shortcuts.

In C# we can use Directory or DirectoryInfo to work with directories. Directory is a static class that provides static methods for working with directories. An instance of a DirectoryInfo provides information about a specific directory.

The classes are available in the System.IO namespace.

C# create directory

A directory is created with the Directory.CreateDirectory() method.

Program.cs
using System;
using System.IO;

namespace CreatingDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var dirName = $@"{docPath}\test";

            DirectoryInfo di = Directory.CreateDirectory(dirName);
            Console.WriteLine($"Full name: {di.FullName}, Name: {di.Name}, Parent: {di.Parent}");

            if (Directory.Exists(dirName))
            {
                Console.WriteLine("Directory exists");
            }
            else
            {
                Console.WriteLine("Directory does not exist");
            }
        }
    }
}

The example creates a new test directory in the user's Documents directory.

var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

We determine the MyDocuments directory path with the Environment.GetFolderPath() method.

var dirName = $@"{docPath}\test";

This is the full path of the directory to be created.

DirectoryInfo di = Directory.CreateDirectory(dirName);
Console.WriteLine($"Full name: {di.FullName}, Name: {di.Name}, Parent: {di.Parent}");

The Directory.CreateDirectory() creates a new directory and returns a DirectoryInfo, which represents the directory at the specified path. From the directory info object, we print the directory's full name, name, and parent.

if (Directory.Exists(dirName))
{
    Console.WriteLine("Directory exists");
}
else
{
    Console.WriteLine("Directory does not exist");
}

With the Directory.Exists() method, we can determine if the specified directory exists.

C# get current directory

The Directory.GetCurrentDirectory() gets the current working directory of the application.

Program.cs
using System;
using System.IO;

namespace CurrentDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            var curDir = Directory.GetCurrentDirectory();
            Console.WriteLine(curDir);

            Console.WriteLine(Directory.GetDirectoryRoot(curDir));
        }
    }
}

The program prints the current working directory (the directory from where the program was run) and its root. The root is determined with the Directory.GetDirectoryRoot().

$ dotnet run
C:\Users\Jano\Documents\csharp\directory\CurrentDirectory
C:\

This is the output.

C# delete directory

A directory is deleted with the Directory.Delete() method.

Program.cs
using System;
using System.IO;

namespace DeleteDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var myDir = $@"{docPath}/test3";

            Directory.CreateDirectory(myDir);
            Console.WriteLine(Directory.Exists(myDir));

            Directory.Delete(myDir);
            Console.WriteLine(Directory.Exists(myDir));
        }
    }
}

The example creates a new directory, checks its existence, deletes it, and finally checks its existence again.

$ dotnet run
True
False

This is the output.

C# move directory

The Directory.Move() moves (renames) a directory.

Program.cs
using System;
using System.IO;

namespace MoveDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var sourceDir = $@"{docPath}\test";
            var destDir = $@"{docPath}\test2";

            Directory.Move(sourceDir, destDir);
        }
    }
}

The example renames a directory.

Directory.Move(sourceDir, destDir);

The parameters of the Directory.Move() method are: the source and the destination directory.

C# list drives

The Directory.GetLogicalDrives() retrieves the names of the logical drives on a computer in the form <drive letter>:\.

Program.cs
using System;
using System.IO;

namespace ListDrives
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] drives = Directory.GetLogicalDrives();

            foreach (string drive in drives)
            {
                System.Console.WriteLine(drive);
            }
        }
    }
}

The example lists all drives on the computer.

C# list directories

The Directory.GetDirectories() returns the names of subdirectories. The subdirectories may meet optional specified criteria.

Program.cs
using System;
using System.IO;

namespace ListDirectories
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string[] myDirs = Directory.GetDirectories(docPath);
            Console.WriteLine("Directories:");

            foreach (var myDir in myDirs)
            {
                Console.WriteLine(myDir);
            }
        }
    }
}

The example lists all subdirectories of the specified directory.

In the next example, we specify some criteria for listed directories.

Program.cs
using System;
using System.IO;

namespace ListDirectories2
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            Console.WriteLine(docPath);

            string[] myDirs = Directory.GetDirectories(docPath, "w*",
                    SearchOption.TopDirectoryOnly);

            Console.WriteLine("Directories:");

            foreach (var myDir in myDirs)
            {
                Console.WriteLine(myDir);
            }
        }
    }
}

The example lists all directories that start with the w character.

string[] myDirs = Directory.GetDirectories(docPath, "w*", SearchOption.TopDirectoryOnly);

The first parameter of the Directory.GetDirectories() is the directory to be listed. The second parameter is the search string to match against the names of subdirectories to be listed. The third parameter specifies whether the search operation should include all subdirectories or only the current directory.

C# list files

The Directory.GetFiles() returns the names of files that meet the (optional) criteria.

Program.cs
using System;
using System.IO;

namespace ListFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string[] myFiles = Directory.GetFiles(docPath);
            Console.WriteLine("Files:");

            foreach (var myFile in myFiles)
            {
                Console.WriteLine(myFile);
            }
        }
    }
}

The example lists all files in the user's Documents directory.

C# directory times

The Directory.GetCreationTime() gets the creation date and time of a directory. The Directory.GetLastAccessTime() gets the date and time the specified file or directory was last accessed. The Directory.GetLastWriteTime() gets the date and time the specified file or directory was last written to.

Program.cs
using System;
using System.IO;

namespace GetTimes
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var myDir = $@"{docPath}\test";

            var creationTime = Directory.GetCreationTime(myDir);
            var lastAccessTime = Directory.GetLastAccessTime(myDir);
            var lastWriteTime = Directory.GetLastWriteTime(myDir);

            Console.WriteLine($"Creation time: {creationTime}");
            Console.WriteLine($"Last access time: {lastAccessTime}");
            Console.WriteLine($"Last write time: {lastWriteTime}");
        }
    }
}

The example prints the creation time, last access time, and the last write time of the specified directory.

C# list entries

The Directory.GetFileSystemEntries() returns the names of all files and subdirectories that meet the specified criteria.

Program.cs
using System;
using System.IO;

namespace ListEntries
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string[] entries = Directory.GetFileSystemEntries(docPath, "w*");
            Console.WriteLine("Entries:");

            foreach (var entry in entries)
            {
                Console.WriteLine(entry);
            }
        }
    }
}

The program lists all entries from the specified directory. The entries must start with the w character.

C# directory size

In the following example, we determine the size of a directory.

Program.cs
using System;
using System.IO;

namespace DirectorySize
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            long size = 0;
            var myDir = $@"{docPath}/csharp";

            var dirInfo = new DirectoryInfo(myDir);

            foreach (FileInfo fi in dirInfo.GetFiles("*", SearchOption.AllDirectories))
            {
                size += fi.Length;
            }

            Console.WriteLine($"The directory size: {size} bytes");
        }
    }
}

To get the size of a directory, we use the DirectoryInfo's GetFiles() method. It returns an array of type FileInfo. The FileInfo's Length property retrieves the size of a file.

foreach (FileInfo fi in dirInfo.GetFiles("*", SearchOption.AllDirectories))
{
    size += fi.Length;
}

We search for all files in the specified directory and its subdirectories. We get the size of each of the retrieved files and add them.

C# copy directory

In the following example, we copy a directory.

Program.cs
using System;
using System.IO;

namespace CopyDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            var source = @"C:\Users\Jano\Documents\websites";
            var dest = @"C:\Users\Jano\Documents\websites-2";

            DirectoryCopy(source, dest, true);

            Console.WriteLine("Copying finished");
        }

        private static void DirectoryCopy(string source, string dest, bool copySubDirs = true)
        {
            var dir = new DirectoryInfo(source);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    $"Source directory does not exist or could not be found: {source}");
            }

            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }

            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)
            {
                string tempPath = Path.Combine(dest, file.Name);
                file.CopyTo(tempPath, false);
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string tempPath = Path.Combine(dest, subdir.Name);
                    DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
                }
            }
        }
    }
}

In the example, we copy a directory and all its subdirectories to a new location.

var source = @"C:\Users\Jano\Documents\websites";
var dest = @"C:\Users\Jano\Documents\websites-2";

We define the source directory and the destination directory.

DirectoryCopy(source, dest, true);

The copying is delegated to the DirectoryCopy() method. The third parameter determines whether to copy subdirectories as well.

var dir = new DirectoryInfo(source);

if (!dir.Exists)
{
    throw new DirectoryNotFoundException(
        $"Source directory does not exist or could not be found: {source}");
}

We create a DirectoryInfo object from the source path. If the directory does not exist, we throw a DirectoryNotFoundException.

DirectoryInfo[] dirs = dir.GetDirectories();

We get all the top-level directories with the GetDirectories() method.

if (!Directory.Exists(dest))
{
    Directory.CreateDirectory(dest);
}

If the destination directory does not exist, we create it.

FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)
{
    string tempPath = Path.Combine(dest, file.Name);
    file.CopyTo(tempPath, false);
}

We get the files in the directory and copy them to the new location.

if (copySubDirs)
{
    foreach (DirectoryInfo subdir in dirs)
    {
        string tempPath = Path.Combine(dest, subdir.Name);
        DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
    }
}

If the copySubDirs is set, we copy subdirectories and their contents to the new location. We recursively call the DirectoryCopy() method.

C# directory access control list

An access control list (ACL) is a list of access control entries (ACE). Each ACE in an ACL identifies a trustee and specifies the access rights allowed, denied, or audited for that trustee.

The DirectoryInfo GetAccessControl() method gets the access control list (ACL) entries for the current directory.

$ dotnet add package System.IO.FileSystem.AccessControl

We need to add the System.IO.FileSystem.AccessControl package.

Program.cs
using System;
using System.IO;
using System.Security.AccessControl;

namespace DirectoryACL
{
    class Program
    {
        static void Main(string[] args)
        {
            var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var myDir = $@"{docPath}\test";

            var dirInfo = new DirectoryInfo(myDir);
            DirectorySecurity dSecurity = dirInfo.GetAccessControl();
            AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true,
                typeof(System.Security.Principal.NTAccount));

            foreach (FileSystemAccessRule ace in acl)
            {
                Console.WriteLine("Account: {0}", ace.IdentityReference.Value);
                Console.WriteLine("Type: {0}", ace.AccessControlType);
                Console.WriteLine("Rights: {0}", ace.FileSystemRights);
                Console.WriteLine("Inherited: {0}", ace.IsInherited);

                Console.WriteLine("------------------------");
            }
        }
    }
}

The example prints the ACL for the specified directory.

var dirInfo = new DirectoryInfo(myDir);

A DirectoryInfo object is created.

DirectorySecurity dSecurity = dirInfo.GetAccessControl();

The GetAccessControl() method returns a DirectorySecurity object that encapsulates the access control rules for the directory.

AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true,
        typeof(System.Security.Principal.NTAccount));

We get a collection of security rules with the GetAccessRules() method.

foreach (FileSystemAccessRule ace in acl)
{
    Console.WriteLine("Account: {0}", ace.IdentityReference.Value);
    Console.WriteLine("Type: {0}", ace.AccessControlType);
    Console.WriteLine("Rights: {0}", ace.FileSystemRights);
    Console.WriteLine("Inherited: {0}", ace.IsInherited);

    Console.WriteLine("------------------------");
}

We enumerate the access control rules in a foreach loop.

In this tutorial, we have worked with directories in C#.

Read C# tutorial or list all C# tutorials.