Home > Backend Development > C++ > How to Easily Extract a Filename (Without Extension) from a Filepath in C#?

How to Easily Extract a Filename (Without Extension) from a Filepath in C#?

Patricia Arquette
Release: 2025-01-25 05:06:17
Original
219 people have browsed it

How to Easily Extract a Filename (Without Extension) from a Filepath in C#?

Use the PATH class to extract the file name from the file path

When processing the file path, it is a common task to extract file name (excluding extension). Traditionally, developers may use string segmentation to achieve this, as shown in the following example:

<code class="language-csharp">string path = "C:\Program Files\hello.txt";
string[] pathArr = path.Split('\');
string[] fileArr = pathArr.Last().Split('.');
string fileName = fileArr.Last().ToString();</code>
Copy after login
Although this method is valid, it looks awkward and easy to make mistakes. Fortunately, the .NET Framework provided a more elegant solution, the PATH class.

Path.getFilename method

Path.getFilename method returns the file name and its extension of the specified file path. This method is usually used to extract only file names, and its grammar is as follows:

<code class="language-csharp">public static string GetFileName(string path);</code>
Copy after login
Path.getFilenamewithoutextation method

The more convenient is Path.GetFilenameWithoutextation method. It does not contain file extension name:

<code class="language-csharp">public static string GetFileNameWithoutExtension(string path);</code>
Copy after login
Using these methods, our code fragment can be simplified to:

<code class="language-csharp">string path = "C:\Program Files\hello.txt";
string fileName = Path.GetFileNameWithoutExtension(path);</code>
Copy after login
Path class provides a set of methods for operation and extraction of file path information. By using these methods, we can simplify the code and improve its readability.

The above is the detailed content of How to Easily Extract a Filename (Without Extension) from a Filepath 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