How to C# Path Class

The System.IO namespace offers smooth solutions for operating through filenames and paths by using functions and methods in the Path class. The purpose of this class, in particular, is to carry out the different operations on String variants containing path information pertaining to files or directories. The members of the Path class are indispensable as they offer developers an elegant and fast way to list the name of a file and its extension.

The Path class in C# provides a range of essential operations that contribute to effective file and directory path management. Some notable operations include:

  1. GetFileName: Retrieves the filename and extension from a given path string.
  2. GetDirectoryName: Retrieves the directory name from a specified path string.
  3. GetExtension: Retrieves the extension from a provided path string.
  4. GetFileNameWithoutExtension: Retrieves the filename without the extension from a given path string.
  5. Combine: Combines multiple path strings into a single, well-formed path.

Get Current Application Path

C# Class application in System.Windows.Forms namespace has static property called ExecutablePath . To get the current application path we can use GetDirectoryName of Path class with ExecutablePath as parameter.

applicationPath = Path.GetDirectoryName(Application.ExecutablePath)

It will return the current directory path of the .exe file .

Full Source C#
using System; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string tmpPath = "c:\\windows\\inf\\wvmic.inf"; string fileExtension = Path.GetExtension(tmpPath); string filename = Path.GetFileName(tmpPath); string filenameWithoutExtension = Path.GetFileNameWithoutExtension(tmpPath); string rootPath = Path.GetPathRoot(tmpPath); string directory = Path.GetDirectoryName(tmpPath); string fullPath = Path.GetFullPath(tmpPath); MessageBox.Show(directory); } } }

Conclusion

Utilizing these important operations within the Path class, developers can efficiently manipulate and extract relevant information from file and directory paths in their C# applications.