C#保留文件路径最后一部分
时间: 2023-08-10 18:05:32 浏览: 79
你可以使用`Path.GetFileName()`方法来获取文件路径的最后一部分,即文件名。下面是一个示例:
```csharp
string filePath = @"C:\Users\Public\Documents\example.txt";
string fileName = Path.GetFileName(filePath);
Console.WriteLine(fileName);
```
输出结果将是 `example.txt`。
相关问题
C#保留文件路径中文件名不加后缀
要保留文件路径中的文件名但不包括文件扩展名,你可以使用`Path.GetFileNameWithoutExtension()`方法。以下是一个示例:
```csharp
string filePath = @"C:\Users\Public\Documents\example.txt";
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
Console.WriteLine(fileNameWithoutExtension);
```
输出结果将是 `example`,即文件名不包含扩展名。
c# 获取文件路径的上一层地址
可以使用C#中的Path类来获取文件路径的上一层地址。具体方法是使用Path.GetDirectoryName方法获取文件路径的目录名,再使用Path.GetDirectoryName方法获取目录名的上一层目录名。
示例代码如下:
```csharp
string filePath = "C:\\Users\\UserName\\Documents\\file.txt";
string directoryPath = Path.GetDirectoryName(Path.GetDirectoryName(filePath));
Console.WriteLine(directoryPath);
```
输出结果为:
```
C:\Users\UserName
```
注意,如果文件路径已经指向根目录,或者根本没有目录名,则第二次调用GetDirectoryName方法会返回null。因此,应该在调用方法之前进行必要的检查。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)