Home >Backend Development >C++ >How to Extract the Folder Name from a File Path in C#?

How to Extract the Folder Name from a File Path in C#?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 03:31:14291browse

How to Extract the Folder Name from a File Path in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn