The methods of System.IO.Path
The base classes in the .net framework are vast and it is commonplace to see coders reinventing the wheel when there is alerady a class or method which will do exactly what they are wanting to do. This is simply just a case of the base class library being so huge.
One of these classes which is often underused and overlooked is System.IO.Path
All of the methods of this class are static and we shall now have a look at these one by one.
These methods are as follows:
- ChangeFileExtension
- CombinePaths
- GetDirectoryName
- GetFileExtension
- GetFileName
- GetFileNameWithoutExtension
- GetFullPath
- GetInvalidFileNameChars
- GetInvalidPathChars
- GetPathRoot
- GetRandomFileName
- GetTempFileName
- GetTempPath
- HasExtension
- IsPathRooted
So we will write a little method to test each of these static methods. We will also write a console app to test these.
So our first method will look like this:
static void ChangeFileExtension(string filePath)
{
ShowHeading("ChangeFileExtension");
Console.WriteLine("The original file is found at {0}", filePath);
Console.WriteLine("The changed file path is {0}", Path.ChangeExtension(filePath, "doc"));
Console.WriteLine();
}
Within here we have made a call to a method called ShowHeading. This is a method we will use which just outputs a heading to the console in yellow which is just for aesthetic reasons and to make the code output more readable.
This ShowHeading method will be as follows:
static void ShowHeading(string heading)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(heading);
Console.ForegroundColor = ConsoleColor.White;
}
Now to test this method, and the other methods once we write them, we will need a console app with a Main method as follows:
static void Main()
{
Console.SetWindowSize(140, 60);
string testPath = @"C:\Users\david.amour\Documents\TestFolder\Test.txt";
ChangeFileExtension(testPath);
Console.Read();
}
Of course you will need to change the testPath to point to some test file on your system. If you then run this you wil see output something like this:
The rest of our test methods and method calls can now be added to out console app. The entire listing is as follows:
And the output when we run this code should look like this:
So System.IO.Path is a simple enough class but has many useful methods which we can use actually quite often but only if we know about these methods. Now you do so make sure you use them!