1 回答
TA贡献1831条经验 获得超4个赞
您不需要在这里使用正则表达式。一种简单的方法是使用File.ReadAllLines读取所有行并简单地将字符添加到所需位置,如以下代码所示:
var sb = new StringBuilder();
string path = @"E:\test\test.txt"; //input file
string path2 = @"E:\test\test2.txt"; //the output file, could be same as input path to overwrite
string charToInsert = " ";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
}
File.WriteAllText(path2, sb.ToString());
在这里我使用不同的输出路径进行测试(不要覆盖输入)
编辑:
修改后的代码循环遍历文件夹中的所有 .txt 文件:
string path = @"C:\TestFolder";
string charToInsert = " ";
string[] allFiles = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly); //Directory.EnumerateFiles
foreach (string file in allFiles)
{
var sb = new StringBuilder();
string[] lines = File.ReadAllLines(file); //input file
foreach (string line in lines)
{
sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
}
File.WriteAllText(file, sb.ToString()); //overwrite modified content
}
- 1 回答
- 0 关注
- 66 浏览
添加回答
举报