Lesson #17 - Introduction to the Path class

The path class resides in the “System.Io” namespace and is used to handle system objects such as folders and files. In this article, I will cover the main methods and properties related to this class with practical examples.


Note: Prior to running any code, please add a reference to the class (using System.IO;)


Example 1: Creating a new file with a different extension


File before the change:


Code:


class Program

{

static void Main(string[] args)

{

//Step 1: determine the Source File

string FileLocation = "C:\\Example 1\\ExampleFile.docx";


//Step 2: Using file and file path to create new files


//File Without Extension:

File.WriteAllText(Path.ChangeExtension(FileLocation, null), "File 1");


//File with specific Extension:

File.WriteAllText(Path.ChangeExtension(FileLocation, ".doc"), "File 2");

}

}


Result:


Example 2: Getting the file properties

In the next code snippet, I will demonstrate a few examples of how to work with file properties including:

  1. Getting the root path for the file

  2. Getting the hosting folder

  3. Getting the full path of the file

  4. Getting the file name

  5. Getting the file extension

  6. Getting the full name


class Program

{

static void Main(string[] args)

{

int counter = 1;


//Getting all files on folder

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


//Getting the files properties using specific conditions

foreach (var filename in FilesInFolder)

{

Console.ForegroundColor = ConsoleColor.Green;

Console.WriteLine("File number in folder: {0}\n", counter);

Console.ResetColor();

Console.WriteLine("File Root drive : {0}", Path.GetPathRoot(filename));

Console.WriteLine("File Directory name : {0}", Path.GetDirectoryName(filename));

Console.WriteLine("File full path : {0}", Path.GetFullPath(filename));

Console.WriteLine("Full file name: {0}", Path.GetFileName(filename));

Console.WriteLine("File name : {0,3}", Path.GetFileNameWithoutExtension(filename));

Console.WriteLine("File extension : {0}", Path.GetExtension(filename));

Console.WriteLine();

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

Console.WriteLine();

counter++;

}

}

}


Result:



1 view0 comments