C#从一个完整路径中取出他的文件名
时间: 2024-03-20 12:44:10 浏览: 15
可以使用System.IO命名空间中的Path类来实现从一个完整路径中取出它的文件名。具体方法是使用Path类的GetFileName方法,示例如下:
```csharp
string fullPath = @"C:\Users\Administrator\Desktop\example.txt";
string fileName = Path.GetFileName(fullPath);
Console.WriteLine(fileName); // 输出:example.txt
```
其中,fullPath为完整路径,fileName为取出的文件名。GetFileName方法会从fullPath中提取出最后一级目录的名称,即文件名。如果fullPath中不包含文件名,则返回空字符串。
相关问题
C#保留文件路径中文件名不加后缀
要保留文件路径中的文件名但不包括文件扩展名,你可以使用`Path.GetFileNameWithoutExtension()`方法。以下是一个示例:
```csharp
string filePath = @"C:\Users\Public\Documents\example.txt";
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
Console.WriteLine(fileNameWithoutExtension);
```
输出结果将是 `example`,即文件名不包含扩展名。
C# 从一个完整的文件路径解析出除去文件名称的文件路径
你可以使用C#中的Path类来解析文件路径,具体实现如下:
```csharp
string filePath = @"C:\Users\JohnDoe\Documents\example.txt";
string directoryPath = Path.GetDirectoryName(filePath);
```
在上面的代码中,`GetDirectoryName`方法返回除去文件名称的文件路径。
执行上述代码后,`directoryPath`的值将为`C:\Users\JohnDoe\Documents`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)