static void Main(string[] args)
{
string path = string.Format(@"C:UsersAdministratorDesktop{0}", @"shenzheng");//根目录
List<string> filePaths = GetAllDirectories(path);//返回根目录下所有文件(包括路径)的集合
foreach (var item in filePaths)
{
StreamReader read = new StreamReader(item, Encoding.UTF8);//根据文件路径获取文件流
string fileName = Path.GetFileNameWithoutExtension(item);//文件名
string filePath = Path.GetDirectoryName(item);//文件所在文件夹
if (!read.EndOfStream)//是否读取完成
{
string aline = read.ReadToEnd();//读取全部------//string aline = read.ReadLine();读取一行
Console.WriteLine(read.ReadLine());
string keyStar = "***";//关键字开始
string ketEnd = "&&&";//关键字结束//获取之间的字符串
int star = aline.IndexOf(keyStar) + keyStar.Length;//加上keyStar所占的位数
int end = aline.IndexOf(ketEnd);
if (star > 0 && end > star)//未找到关键字
{
string newstr = aline.Substring(star, end - star);
Console.WriteLine(newstr);//打印到控制台,查看是否截取想要的信息
Console.WriteLine(fileName + "打印完毕");
//char[] dd = new char[] { ']', ',' };
string[] strs = newstr.Split(new string[] { "分割字符串" }, StringSplitOptions.RemoveEmptyEntries);//根据规则分割你想要的字符串获得字符串集合
StreamWriter sw = new StreamWriter(@"C:UsersAdministratorDesktopout" + fileName + "处理.txt", false);//输出目录及文件名称定义
for (int i = 0; i < strs.Count(); i++)
{
Console.WriteLine(strs[i] + "," + (i + 1).ToString());//打印到控制台
sw.WriteLine(strs[i] + "," + (i + 1).ToString());//写到文件
sw.Flush();//清空StreamWriter缓存,否则会写不全
Thread.Sleep(20);
}
Console.WriteLine(fileName + "写入完毕");
Console.ReadKey();
}
else
{
Console.WriteLine("当前文档" + fileName + "没有符合规则的数据,跳过!");
}
}
}
static List<string> filesList = new List<string>();
public static List<string> GetAllDirectories(string rootPath)
{
string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
foreach (string path in subPaths)
{
GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
}
string[] files = Directory.GetFiles(rootPath);
foreach (string file in files)
{
filesList.Add(file);//将当前目录中的所有文件全名存入文件List
}
return filesList;
}
}