C# facilities for dealing with folders

Especially for batch applications, the ability to deal with folders is important. This post documents the C# facilities that can give our applications the ability to work with folders.

Get the folder path which the executing binary is running in

string exeFolderPath 
    = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

Check whether a folder exists

// Check if there is a folder named as techcoil in the same directory
// as the running executable.
if (System.IO.Directory.Exists(Path.Combine(exeFolderPath, "techcoil")))
    Console.WriteLine("Folder exists.");
    Console.WriteLine("Folder does not exists.");
} // end if

Create a folder

// Create a folder named as techcoil in the same folder as the 
// executing binary.
Directory.CreateDirectory(Path.Combine(exeFolderPath, "techcoil"));

Rename a folder

// Rename the folder from techcoil to new_techcoil
Directory.Move("techcoil", "new_techcoil");

Delete a folder

// Delete the folder named as techcoil that exists in the same folder as the 
// executing binary, recursively. 
Directory.Delete(Path.Combine(exeFolderPath, "techcoil"), true);

Get some information about a folder

DirectoryInfo techcoilInfo = new DirectoryInfo("techcoil");
// Get the time when the folder is first created
// Get the full path of the directory
// Get the last occurence when the folder is being accessed
// Get the last occurence when the folder is written to
// Get the full name of the parent folder of techcoil

Get list of files in a folder

// Get a list of pathnames of files that are in the techcoil folder.
IEnumerable<string> filesInTechcoil = Directory.EnumerateFiles("techcoil");

// Print the list of pathnames 
foreach (string filePath in filesInTechcoil) 
} // end foreach

Get a list of folders in a folder

// Get the pathnames 
IEnumerable<string> foldersInTechcoil = Directory.EnumerateDirectories("techcoil");
foreach (string folderPath in foldersInTechcoil)
} // end foreach

External references

Related posts

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.