How to C# Path Class

The System.IO namespace offers efficient solutions for handling filenames and paths, with the assistance of the Path class. This class is specifically designed to perform various operations on String instances that contain file or directory path information. By using the members of the Path class, developers can easily and swiftly execute common tasks such as extracting filenames and extensions.

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.