c# 检索指定文件夹下所有文件以及子文件夹下文件的字符串,获取"sfun.UpOperation("和“)”之间的字符串
时间: 2024-02-12 07:07:25 浏览: 127
你可以使用 C# 的 `Directory.GetFiles` 和 `Directory.GetDirectories` 方法获取指定文件夹下的所有文件和子文件夹,然后对每个文件使用 `File.ReadAllText` 方法读取文件内容,最后使用正则表达式获取目标字符串。
以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string folderPath = "your_folder_path";
string pattern = @"sfun\.UpOperation\((.*?)\)";
List<string> files = new List<string>();
files.AddRange(Directory.GetFiles(folderPath));
foreach (string folder in Directory.GetDirectories(folderPath))
{
files.AddRange(Directory.GetFiles(folder, "*", SearchOption.AllDirectories));
}
foreach (string filePath in files)
{
string fileContent = File.ReadAllText(filePath);
MatchCollection matches = Regex.Matches(fileContent, pattern, RegexOptions.Singleline);
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}
}
```
其中,`folderPath` 是指定的文件夹路径,`pattern` 是正则表达式模式,`RegexOptions.Singleline` 标志表示让 `.` 匹配任何字符,包括换行符。代码中使用 `List<string>` 存储所有文件路径,`Directory.GetFiles` 方法获取当前文件夹下的所有文件路径并加入到列表中,`Directory.GetDirectories` 方法获取当前文件夹下的所有子文件夹路径并循环遍历,对于每个子文件夹,使用 `Directory.GetFiles` 方法获取所有文件路径并加入到列表中。最后,使用 `foreach` 循环遍历所有文件,对于每个文件,使用 `File.ReadAllText` 方法读取文件内容,然后使用 `Regex.Matches` 方法匹配所有目标字符串。如果匹配成功,则输出匹配结果的第一个分组内容,即括号内的内容。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)