Home >Backend Development >C++ >How to Easily Extract a Filename (Without Extension) from a Filepath in C#?
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>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
<code class="language-csharp">public static string GetFileName(string path);</code>Path.getFilenamewithoutextation method
<code class="language-csharp">public static string GetFileNameWithoutExtension(string path);</code>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>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!