C# 获取路径目录名
时间: 2023-08-31 22:10:51 浏览: 69
可以使用 `Path.GetDirectoryName` 方法来获取路径的目录名。以下是一个示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Projects\MyFile.txt";
string directoryName = Path.GetDirectoryName(path);
Console.WriteLine(directoryName);
}
}
```
在上述示例中,`path` 变量存储了文件的完整路径,`Path.GetDirectoryName` 方法会返回该路径的目录名。在这个例子中,输出将会是 `C:\Projects`。
相关问题
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# 根据路径获取的最后一个目录的名字
你可以使用 `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` 属性获取这个目录的名字。
相关推荐
![](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)