top of page

C# Tutorial For Beginners: Introduction to the Path class

Updated: Jan 19, 2022

The path class resides in the “System.Io” namespace and handles system objects such as folders and files. This article will cover the main methods and properties related to this class with practical examples.


Note: Before 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 following 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:



13 views0 comments