Developers often need to know certain aspects of a file such as the name, full path, drive, and file extension. The .NET Framework provides easy access to these details via the Path class contained in the System.IO namespace. This article examines the various pieces of information available in the Path class with a focus on .NET Framework 2.0.

The Path class

The Path class allows you to work with file path values. A key aspect of the class is the fact that it uses string values to perform all of its operations. This may not seem like a big deal, but the string may be an actual file name or a random string. You should utilise other classes, such as the File class, to confirm the existence of a file. The class provides various properties and methods to perform operations.

Path
Many of the methods contained in the Path class accept a path as a parameter. A path is a string that provides the location of a file or directory. A path does not necessarily point to a location on disk. The exact format of a path is determined by the current platform. A path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name.

Methods
The following list provides a sampling of the methods available in the Path class:

|> ChangeExtension: Allows you to change the file extension of a path string.
|> Combines: Allows you to combine two path strings into one.
|> GetDirectoryName: Returns the directory information included in a path string.
|> GetExtension: Returns the extension included in a path string.
|> GetFileName: Returns the file name and extension of a path string.
|> GetFileNameWithoutExtension: Returns the file name without the extension for a path string.
|> GetFullPath: Returns the absolute path for a path string.
|> GetInvalidFileNameChars: Returns a character array containing the characters not allowed in file names.
|> GetPathRoot: Returns the root directory information for a path string.
|> GetRandomFileName: Returns a random file or folder name.
|> GetTempFileName: A uniquely named, zero-byte temporary file is created with the full path returned.
|> GetTempPath: The path to the system's temporary directory is returned.
|> HasExtension: Determines if a path string contains an extension (true) or not (false).
|> IsPathRooted: Gets a value indicating whether the specified path string contains absolute or relative path information.

The best way to understand how to use these methods is with an example. The C# sample in Listing A provides a peek at using the Path class. Listing B contains the equivalent VB.NET code.

Listing A

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace PathClassCSharp {
class Program {
static void Main(string[] args){
string testPath;
string p1;
string p2;
char[] fnChars;
inti;
testPath = "c:\\techrepublic.txt";
p1 = "c:\\";
p2 = "test.exe";
Console.WriteLine("Directory name: " + Path.GetDirectoryName(testPath));
if (Path.HasExtension(testPath)) {
Console.WriteLine("File extension: " + Path.GetExtension(testPath));
}
Console.WriteLine("Filename: " + Path.GetFileName(testPath));
Console.WriteLine("Filename w/o ext: " + Path.GetFileNameWithoutExtension(testPath));
Console.WriteLine("Full path: " + Path.GetFullPath(testPath));
fnChars = Path.GetInvalidFileNameChars();
if (Path.IsPathRooted(testPath)) {
Console.WriteLine("Root: " + Path.GetPathRoot(testPath));
}
Console.WriteLine("Random file name: " + Path.GetRandomFileName());
Console.WriteLine("Temp file name: " + Path.GetTempFileName());
if (File.Exists(testPath)) {
Console.WriteLine("File does exist.");
}
if (File.Exists(Path.Combine(p1, p2))) {
Console.WriteLine("The file " + Path.Combine(p1, p2) + " exists.");
} else {
Console.WriteLine("The file " + Path.Combine(p1, p2) + " does not exist.");
} } } }

Listing B

Module Module1
Sub Main()
Dim testPath As String
Dim p1 As String
Dim p2 As String
Dim fnChars As Char()
testPath = "c:\techrepublic.txt"
p1 = "c:\"
p2 = "test.exe"
Console.WriteLine("Directory name: " + Path.GetDirectoryName(testPath))
If (Path.HasExtension(testPath)) Then
Console.WriteLine("File extension: " + Path.GetExtension(testPath))
End If
Console.WriteLine("Filename: " + Path.GetFileName(testPath))
Console.WriteLine("Filename w/o ext: " + Path.GetFileNameWithoutExtension(testPath))
Console.WriteLine("Full path: " + Path.GetFullPath(testPath))
fnChars = Path.GetInvalidFileNameChars()
If (Path.IsPathRooted(testPath)) Then
Console.WriteLine("Root: " + Path.GetPathRoot(testPath))
End If
Console.WriteLine("Random file name: " + Path.GetRandomFileName())
Console.WriteLine("Temp file name: " + Path.GetTempFileName())
If (File.Exists(testPath)) Then
Console.WriteLine("File does exist.")
End If
If (File.Exists(Path.Combine(p1, p2))) Then
Console.WriteLine("The file " + Path.Combine(p1, p2) + " exists.")
Else
Console.WriteLine("The file " + Path.Combine(p1, p2) + " does not exist.")
End If
End Sub
End Module

This simple application displays various characteristics of the path string used. (Note: A character array is populated with the results of a call to the GetInvalidFileNameChars method, but the contents of the character array are not displayed due to problems with displaying such characters on the Web.) The latter portion of the application determines if the file path exists via the Exists method of the File class. Finally, the Combines method concatenates two values into one path string. The output of the application (on my system) follows:

Directory name: c:\
File extension: .txt
Filename: techrepublic.txt
Filename w/o ext: techrepublic
Full path: c:\techrepublic.txt
Root: c:\
Random file name: km54krxb.s1g
Temp file name: C:\Documents and Settings\tpatton\Local Settings
\Temp\tmp5D2F.tmp
File does exist.
The file c:\test.exe does not exist.

Properties
The Path class provides properties as well. These properties allow you to manipulate various elements of path strings and how the system handles characters within it. The follow list provides an overview of these properties:

|> AltDirectorySeparatorChar: Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organisation. The value of this property is a backslash (\) on UNIX and a slash (/) on Windows and Macintosh operating systems.
|> DirectorySeparatorChar: Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organisation. The value of this property is a backslash (\) on UNIX, and a slash (/) on Windows and Macintosh operating systems.
|> PathSeparator: A platform-specific separator character used to separate path strings in environment variables. On Windows-based desktop platforms, the value of this field is the semicolon (;) by default, but it might vary on other platforms.
|> VolumeSeparatorChar: Provides a platform-specific volume separator character. The value of this field is a colon (:) on Windows and Macintosh, and a slash (/) on UNIX operating systems.

A simple code snippet allows you to view these properties on your system as the C# example in Listing C illustrates. Listing D contains the equivalent VB.NET code.

Listing C

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace PathClassCSharp2 {
class Program {
static void Main(string[] args){
Console.WriteLine("AltDirectorySeparatorChar - " + Path.AltDirectorySeparatorChar);
Console.WriteLine("DirectorySeparatorChar - " + Path.DirectorySeparatorChar);
Console.WriteLine("PathSeparator - " + Path.PathSeparator);
Console.WriteLine("VolumeSeparatorChar - " + Path.VolumeSeparatorChar);
} } }

Listing D

Module Module1
Sub Main()
Console.WriteLine("AltDirectorySeparatorChar - " + Path.AltDirectorySeparatorChar)
Console.WriteLine("DirectorySeparatorChar - " + Path.DirectorySeparatorChar)
Console.WriteLine("PathSeparator - " + Path.PathSeparator)
Console.WriteLine("VolumeSeparatorChar - " + Path.VolumeSeparatorChar)
End Sub
End Module

The following output is generated on my system:

AltDirectorySeparatorChar - /
DirectorySeparatorChar - \
PathSeparator - ;
VolumeSeparatorChar - :

The path to success

The .NET Path class provides a simple and straightforward way to access information about a file and its path. This includes the name of the file, directory information, and the details of the file extension assigned to the file. This allows you to quickly extract the necessary data and move forward. Combine it with the remaining classes of the System.IO namespace, and you have a powerful set of tools for working with files.

Cast your .NET This was published in Cast your .NET, check every Thursday for more stories

Related links

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

Log in


Sign up | Forgot your password?

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

  • Staff Microsoft showcases new NUIs

    TechFest, Microsoft's internal even took place this week with researchers showcasing some new interfaces the company is working on. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!