C# 读取文件夹之后的路径保存到集合中
时间: 2024-01-16 19:04:01 浏览: 52
可以使用 `Directory.GetFiles` 方法来获取指定文件夹下的所有文件路径,然后将其保存到一个集合中。以下是一个示例代码:
```csharp
using System.Collections.Generic;
using System.IO;
public static List<string> GetFilePaths(string folderPath)
{
List<string> filePaths = new List<string>();
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
filePaths.Add(file);
}
return filePaths;
}
```
调用示例:
```csharp
string folderPath = @"C:\MyFolder";
List<string> filePaths = GetFilePaths(folderPath);
foreach (string filePath in filePaths)
{
Console.WriteLine(filePath);
}
```
这里的 `GetFilePaths` 方法接收一个文件夹路径作为参数,返回一个包含该文件夹中所有文件路径的字符串集合 `filePaths`。然后我们使用 `Directory.GetFiles` 方法获取所有文件路径,并使用 `foreach` 循环将其添加到集合中。最后,我们返回集合。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)