C#System.IO.Path.Combine
时间: 2024-03-10 11:45:05 浏览: 27
`System.IO.Path.Combine()` 方法可以将多个字符串组合成一个路径。它会自动处理路径分隔符,以确保生成的路径是正确的。
示例代码:
```csharp
string dirPath = @"C:\Users\username\Documents";
string fileName = "example.txt";
string fullPath = Path.Combine(dirPath, fileName);
Console.WriteLine(fullPath); // 输出:C:\Users\username\Documents\example.txt
```
在这个示例中,`Path.Combine()` 方法将 `dirPath` 和 `fileName` 这两个字符串合并成一个完整的路径 `fullPath`,并且自动处理了路径分隔符。需要注意的是,`Path.Combine()` 方法并不会检查生成的路径是否为合法路径,如果其中包含非法字符,可能会导致路径操作失败。
如果需要同时合并多个路径,可以在 `Path.Combine()` 方法中传入多个字符串参数,例如:
```csharp
string basePath = @"C:\Users\username\Documents";
string subPath1 = "example";
string subPath2 = "subfolder";
string fileName = "example.txt";
string fullPath = Path.Combine(basePath, subPath1, subPath2, fileName);
Console.WriteLine(fullPath); // 输出:C:\Users\username\Documents\example\subfolder\example.txt
```
在这个示例中,`Path.Combine()` 方法合并了 `basePath`、`subPath1`、`subPath2` 和 `fileName` 这四个字符串,生成了一个完整的路径。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)