Home >Backend Development >C++ >How Can I Programmatically Extract the Last Folder Name from a File Path in C#?

How Can I Programmatically Extract the Last Folder Name from a File Path in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 01:27:09241browse

How Can I Programmatically Extract the Last Folder Name from a File Path in C#?

Determining the Folder Name from a File Path

When working with file paths, it's often necessary to extract the folder name associated with a given file. For instance, consider the path:

string path = "C:\folder1\folder2\file.txt";

How can we programmatically retrieve the "folder2" string from this path?

Solution

One approach is to leverage the Path.GetFileName and Path.GetDirectoryName methods. The GetDirectoryName method returns the full path of the parent directory, while GetFileName returns the name of the last path component (typically a file name). By combining these methods, we can obtain the desired folder name:

string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

This approach works effectively regardless of whether the path exists on the file system. However, it assumes that the path ends in a file name. If the path may end in a folder name instead, it's advisable to check for the existence of a file or folder at the location before proceeding.

The above is the detailed content of How Can I Programmatically Extract the Last 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