Sunday, February 12, 2012

Working with Path Class in .Net (C#)

Path class is static class and has collection of static methods and fields. Path class is available in System.IO namespace. Path provides the location of file or folder located on disk. Path class used to perform operations like getting file name and extension part of the URL, combining two strings into single path, getting temp directory path etc. Let's have a look on major operations using Path.

string path = @"d:\temp\test.txt";

Console.WriteLine("File Name: {0}",Path.GetFileName(path));
Console.WriteLine("Full Path: {0}",Path.GetFullPath(path));
Console.WriteLine("Extension: {0}",Path.GetExtension(path));
Console.WriteLine("Directory Name: {0}",Path.GetDirectoryName(path));
Console.WriteLine("Path Root: {0}",Path.GetPathRoot(path));
Console.WriteLine("File Name w/o extn: {0}",Path.GetFileNameWithoutExtension(path));
Console.WriteLine("Has Extn: {0}",Path.HasExtension(path));
Console.WriteLine("Temp Path: {0}", Path.GetTempPath());
Console.WriteLine("Directory Seperator: {0}", Path.AltDirectorySeparatorChar);
Console.WriteLine("Volume Seperator: {0}", Path.VolumeSeparatorChar);
Console.WriteLine("Combine : {0}", Path.Combine("Dir1","File1.txt"));

Output –
File Name: test.txt
Full Path: d:\temp\test.txt
Extension: .txt
Directory Name: d:\temp
Path Root: d:\
File Name w/o extn: test
Has Extn: True
Temp Path: C:\Users\msureja\AppData\Local\Temp\
Directory Seperator: /
Volume Seperator: :
Combine : Dir1\File1.txt

See Also - 

No comments:

Post a Comment