在一个路径的ArrayList中根据文件名查找文件列表
时间: 2024-11-04 07:11:12 浏览: 23
在一个 `ArrayList` 中存储了文件路径的情况下,如果你需要根据文件名查找特定文件,你可以遍历这个列表并比较每个文件的名称。以下是基本步骤:
1. 创建一个 `ArrayList` 并填充文件路径:
```csharp
ArrayList filePaths = new ArrayList();
filePaths.Add(@"C:\path\to\file1.txt");
filePaths.Add(@"C:\path\to\file2.docx");
filePaths.Add(@"C:\path\to\file3.png");
```
2. 定义一个函数来搜索文件名:
```csharp
public bool FindFileByName(string fileName)
{
foreach (string path in filePaths)
{
if (System.IO.File.Exists(path) && System.IO.Path.GetFileName(path).Equals(fileName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false; // 没找到对应的文件
}
```
这里使用 `System.IO.File.Exists` 判断路径是否指向实际存在的文件,并通过 `Path.GetFileName` 获取文件名部分。
3. 调用该函数并传入你要查找的文件名:
```csharp
string searchFileName = "file2";
bool found = FindFileByName(searchFileName);
if (found)
{
Console.WriteLine($"找到了文件: {searchFileName}");
}
else
{
Console.WriteLine($"未找到文件: {searchFileName}");
}
```
阅读全文
相关推荐



















