last modified July 5, 2023
C# Directory tutorial shows how to work with directories in C#. In our exampleswe create directories, delete them, list directories or get their permissions.
C# list directory tutorial focuses onlisting directory contents in C#.
Directory definition
A directory, also called a folder, is a location for storing files on yourcomputer. In addition to files, a directory also stores other directoriesor shortcuts.
In C# we can use Directory
or DirectoryInfo
to workwith directories. Directory
is a static class that provides staticmethods 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
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'sDocuments
directory.
var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
We determine the MyDocuments
directory path with theEnvironment.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 aDirectoryInfo
, which represents the directory at the specifiedpath. 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 specifieddirectory exists.
C# get current directory
The Directory.GetCurrentDirectory
gets the current workingdirectory of the application.
Program.cs
var curDir = Directory.GetCurrentDirectory();Console.WriteLine(curDir);Console.WriteLine(Directory.GetDirectoryRoot(curDir));
The program prints the current working directory (the directory from where theprogram was run) and its root. The root is determined with theDirectory.GetDirectoryRoot
.
$ dotnet runC:\Users\Jano\Documents\csharp\directory\CurrentDirectoryC:\
C# delete directory
A directory is deleted with the Directory.Delete
method.
Program.cs
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, andfinally checks its existence again.
$ dotnet runTrueFalse
C# move directory
The Directory.Move
moves (renames) a directory.
Program.cs
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 andthe destination directory.
C# list drives
The Directory.GetLogicalDrives
retrieves the names of the logicaldrives on a computer in the form <drive letter>:\
.
Program.cs
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
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
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 thedirectory to be listed. The second parameter is the search string to matchagainst the names of subdirectories to be listed. The third parameter specifieswhether the search operation should include all subdirectories or only thecurrent directory.
C# list files
The Directory.GetFiles
returns the names of files thatmeet the (optional) criteria.
Program.cs
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 adirectory. The Directory.GetLastAccessTime
gets the date and timethe specified file or directory was last accessed. TheDirectory.GetLastWriteTime)
gets the date and time the specifiedfile or directory was last written to.
Program.cs
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 writetime of the specified directory.
C# list entries
The Directory.GetFileSystemEntries
returns the names of all filesand subdirectories that meet the specified criteria.
Program.cs
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 muststart with the w
character.
C# directory size
In the following example, we determine the size of a directory.
Program.cs
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
var source = @"C:\Users\Jano\Documents\websites";var dest = @"C:\Users\Jano\Documents\websites-2";DirectoryCopy(source, dest, true);Console.WriteLine("Copying finished"); 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 thirdparameter 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 thedirectory 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 theircontents 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 rightsallowed, denied, or audited for that trustee.
The DirectoryInfo
GetAccessControl
methodgets 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.Security.AccessControl;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 objectthat 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.
Source
Directory class - language reference
In this article we have worked with directories in C#.
Author
My name is Jan Bodnar and I am a passionate programmer with many years ofprogramming experience. I have been writing programming articles since 2007. Sofar, I have written over 1400 articles and 8 e-books. I have over eight years ofexperience in teaching programming.
List all C# tutorials.