C# 根据路径获取的最后一个目录的名字
时间: 2024-01-21 16:18:41 浏览: 39
你可以使用 `System.IO.Path` 类的 `GetDirectoryName` 方法和 `System.IO.Directory` 类的 `GetParent` 方法来实现。以下是一个例子:
```csharp
string path = @"C:\Users\Username\Documents\ExampleFolder\ExampleFile.txt";
string folderName = new DirectoryInfo(Path.GetDirectoryName(path)).Name;
Console.WriteLine(folderName); // 输出 ExampleFolder
```
在这个例子中,我们首先使用 `Path.GetDirectoryName` 方法来获取路径中的目录名(`@"C:\Users\Username\Documents\ExampleFolder"`),然后使用 `DirectoryInfo` 类来获取这个目录的信息,再使用 `.Name` 属性获取这个目录的名字。
相关问题
C# 根据路径获取所在的目录名
可以使用 `System.IO.Path` 类中的 `GetDirectoryName` 方法来获取路径中的目录名。该方法将返回指定路径字符串的目录信息。
以下是示例代码:
```csharp
string path = @"C:\Users\username\Documents\file.txt";
string directoryName = Path.GetDirectoryName(path);
Console.WriteLine(directoryName); // 输出:C:\Users\username\Documents
```
上述代码中,`path` 变量存储了要获取目录名的路径。`Path.GetDirectoryName(path)` 方法返回路径中的目录名,并将其存储在 `directoryName` 变量中。最后,将目录名输出到控制台上。
C#获得一个路径的上一层路径
要在C#中获取一个路径的上一层路径,可以使用 `Path.GetDirectoryName()` 方法。这个方法会返回指定路径的父目录路径。
以下是一个示例代码:
```csharp
using System.IO;
string path = "C:\\folder\\subfolder\\file.txt";
string parentPath = Path.GetDirectoryName(path);
```
在上面的示例中,我们使用 `Path.GetDirectoryName()` 方法来获取路径 `"C:\\folder\\subfolder\\file.txt"` 的父目录路径。这个方法会返回 `"C:\\folder\\subfolder"`。
请注意,`Path.GetDirectoryName()` 方法返回的是一个字符串,可能为空(如果路径是根目录或无效路径)。在使用这个方法之前,确保你已经检查了路径的有效性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)