Extracting the Folder Name from a File Path
When working with file paths, it can be necessary to extract the folder name from the full path. This allows you to identify the location of the file within the directory structure. Here's how to do it in C#:
Using the Path class, there are two approaches to obtain the folder name:
Approach 1: Combining GetDirectoryName and GetFileName
This method is straightforward and returns the last folder name in the path:
string path = "C:/folder1/folder2/file.txt"; string lastFolderName = Path.GetFileName(Path.GetDirectoryName(path));
Approach 2: Using Path.GetFileName on the Parent Directory
This method considers the parent directory as the folder name:
string path = "C:/folder1/folder2/file.txt"; string folderName = Path.GetFileName(Path.GetDirectoryName(path));
Both approaches provide the folder name. However, the second approach relies on the assumption that the path ends in a filename. If the path represents a folder instead, you may need to handle it differently.
The above is the detailed content of How to Extract the Folder Name from a File Path in C#?. For more information, please follow other related articles on the PHP Chinese website!