Many times in application development using C# it is required to get the directory from a file's full path.
Let us say we need to find the directory for the following path:
string path = @"C:\Directory\File.txt";
If the requirement is to get the absolute path use the below:
string absolutePath = Path.GetDirectoryName(path)
If the requirement is to get relative name use the below:
string relativeName = FileInfo(path).Directory.FullName.
If the requirement is to get the file name use the below:
string filename = Path.GetFileName(path);
If the requirement is to get the file name without extension use the below:
string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
Note that Path and FileInfo are both found in the namespace System.IO.
We should ensure that path is valid as below:
1) The path parameter should not contain invalid characters, is empty, or contains only white spaces.
2) The path parameter is not longer than the system-defined maximum length.
0 Comment(s)