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
Release: 2024-12-29 03:31:14
Original
286 people have browsed it

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));
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template