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.");
}
else
{
    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
Console.WriteLine(techcoilInfo.CreationTime);
// Get the full path of the directory
Console.WriteLine(techcoilInfo.FullName);
// Get the last occurence when the folder is being accessed
Console.WriteLine(techcoilInfo.LastAccessTime);
// Get the last occurence when the folder is written to
Console.WriteLine(techcoilInfo.LastWriteTime);
// Get the full name of the parent folder of techcoil
Console.WriteLine(techcoilInfo.Parent.FullName);

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) 
{
    Console.WriteLine(filePath);
} // end foreach

Get a list of folders in a folder

// Get the pathnames 
IEnumerable<string> foldersInTechcoil = Directory.EnumerateDirectories("techcoil");
foreach (string folderPath in foldersInTechcoil)
{
    Console.WriteLine(folderPath);
} // 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.