C# Tutorial For Beginners: Working with File System Objects

Updated: Aug 22

In this article, I will review the System.IO namespaces and its main classes that we can use to work with file system objects.


The Directory Class

This class contains static methods for Directories manipulation, The table below contains the main methods you can use while working with this class:

Code Examples

class Program

{

static void Main(string[] args)

{

//Example 1: Delete a specific folder

Directory.Delete("C:\\Folder 1\\Folder 2");

//OR

Directory.Delete("C:\\Folder 1\\Folder 2", true);//In case that folder has files


//Example 2: Creating two folders “Folder 1” and an inner folder “Folder 2”

Directory.CreateDirectory("C:\\Folder 1\\Folder 2");


//Example 3: Get list of files in a given folder

string[] FilesInFolder = Directory.GetFiles("C:\\Folder 1");


foreach (var file in FilesInFolder)

{

Console.WriteLine(file); //Will print list of files under folder "Example 1"

}


//Example 4: Get a folder list under specific path

string[] ArrayOfDirectories = Directory.GetDirectories("c:\\");

foreach (var item in ArrayOfDirectories)

{

Console.WriteLine(item);

}


//Example 5: Getting the folder creation time

DateTime FolderCreation2 = Directory.GetCreationTime("c:\\Folder 1");


//Example 6: Getting the parent folder of a specific path

Directory.GetParent("c:\\Folder 1\\Folder 2"); //Will return "Folder 1"


//Example 7: Get logical Drives

string[] LogicalDrives = Directory.GetLogicalDrives();


foreach (var item in LogicalDrives)

{

Console.WriteLine(item);

}


//Example 8: Check for folder existence under a specific path

if (Directory.Exists("C:\\Folder 1") == true)

{

Console.WriteLine("Directory Exists");

}

else

{

Console.WriteLine("Directory Not Exists");

}


//Example 9: Move a folder to a different location

Directory.Move("c:\\Folder 1\\Folder 2", "c:\\Folder 2");// Wiil MOVE folder 2 under C: drive


}

}



The DirectoryInfo Class

This table contains the main methods you can use while working with this class.

Code Examples


class Program

{

static void Main(string[] args)

{

DirectoryInfo DirectoryInfoInstance = new DirectoryInfo("c:\\Code\\Code");


//Example 1: Create the "Code" folder under C root

DirectoryInfoInstance.Create();


//Example 2: Getting the parent folder of the instance

Console.WriteLine(DirectoryInfoInstance.Parent);//Will return "Code"


//Example 3: Validate Folder existence

if (DirectoryInfoInstance.Exists == true)

{

Console.WriteLine("Folder exist");

}

else

{

Console.WriteLine("Folder Not exist");

}


//Example 4: Getting the Folder creation time

Console.WriteLine(DirectoryInfoInstance.CreationTime);


//Example 5: Getting instance name

Console.WriteLine(DirectoryInfoInstance.Name);


//Example 6: Getting the full path of the instance

Console.WriteLine(DirectoryInfoInstance.FullName);


//Example 7: Getting the root partition of the instance

Console.WriteLine(DirectoryInfoInstance.Root);


//Example 8: Getting the root partition of the instance

Console.WriteLine(DirectoryInfoInstance.Attributes);

}

}




The File Class

Code Examples

static void Main(string[] args)

{

Directory.CreateDirectory("C:\\Working With Files");


//File Creation options:

//Example 1: Create three new files under specific path

for (int i = 0; i < 3; i++)

{

File.Create("C:\\Working With Files\\File_" + i + ".txt");

}


//Example 2: Create a file with Encryption

File.Create("C:\\Working With Files\\FileWithACLS.txt",1024,FileOptions.Encrypted);


//Example 3: Create a file with specific ACL's

FileSecurity FileSecuority = new FileSecurity();

FileSecuority.AddAccessRule(new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, AccessControlType.Allow));

File.Create("File_0.txt", 333, FileOptions.Asynchronous, FileSecuority);


//Example 4: Add a new ACL to a file

FileSecurity AddAcl = new FileSecurity();

AddAcl.AddAccessRule(new FileSystemAccessRule(@"Administrator", FileSystemRights.Read, AccessControlType.Deny));

File.SetAccessControl("File_0.txt", AddAcl);


//Example 5: Adding permission to a user

FileSecurity AddAcl2 = new FileSecurity();

AddAcl.AddAccessRule(new FileSystemAccessRule(@"Administrator", FileSystemRights.FullControl, AccessControlType.Allow));

File.SetAccessControl("c:\\File_0.txt", AddAcl2);


//Example 6: Remove an ACL from a file

FileSecurity RemoveAcl = new FileSecurity();

AddAcl.RemoveAccessRule(new FileSystemAccessRule(@"Administrator", FileSystemRights.FullControl, AccessControlType.Allow));

File.SetAccessControl("c:\\File_0.txt", RemoveAcl);


//---------------------------

//Example 1: File Copy (True = Overwrite if existing )

File.Copy("c:\\Source file.txt", "D:\\Destination", true);


//Example 2: File Delete

File.Delete("c:\\File_0.txt");


//Example 3: Check if a file exists (return True OR False)

File.Exists("c:\\File_0.txt");


//Example 4: File Move (“Cut-> Paste”)

File.Move("c:\\1.txt", "c:\\1\\1.txt");//Moving the file with the same name

File.Move("c:\\1.txt", "c:\\NewName.txt");//Moving the file and change its name


//Example 5: File Information

DateTime FileCreationDate = File.GetCreationTime("c:\\File_0.txt");

DateTime FileLastAccess = File.GetLastAccessTime("c:\\File_0.txt");

DateTime FileLastWriteTime = File.GetLastWriteTime("c:\\File_0.txt");


Console.WriteLine(@"The file created on : {0}

The file last accessed in : {1}

The last modification on file : {2}"

, FileCreationDate, FileLastAccess, FileLastWriteTime);

}

}



Additional methods which we can use to work with file content:


Code Examples

class Program

{

static void Main(string[] args)

{

//Example 1: Append new lines to a file


string[] text = { "Line1", "Line2", "Line3" };

File.AppendAllLines("c:\\File1.txt", text, Encoding.UTF8);

//Or

File.AppendAllLines("c:\\NewFile.txt", new string[] { "1", "2" }, Encoding.Default);


//Example 2: Read all lines from a file (ReadAllLines) and add them to a string array

string[] FileLines = File.ReadAllLines("c:\\File1.txt", Encoding.UTF8);

foreach (var LineInFile in FileLines)

{

Console.WriteLine(LineInFile);

}


//Example 3: Read all text from a file (ReadAllLines) and add them to a single string

string FileContent = File.ReadAllText("c:\\File1.txt", Encoding.UTF8);

Console.WriteLine(FileContent);

}