我通过使用两种不同的方式中,第一完成这一点:文件读入内存,并使用正则表达式或替换字符串替换。然后我将整个字符串附加到一个临时文件。
第二个是通过读取由线临时文件线和手动构建使用StringBuilder的每行和每追加处理线的结果文件中。
第方法适用于一般的正则表达式替换,但如果您尝试做做Regex.Matches在一个大的文件它会占用内存。
static void ProcessLargeFile()
{
if (File.Exists(outputDefsFileName)) File.Delete(outputDefsFileName);
if (File.Exists(defTempProc1FileName)) File.Delete(defTempProc1FileName);
if (File.Exists(defTempProc2FileName)) File.Delete(defTempProc2FileName);
string text = File.ReadAllText(inputDefsFileName, Encoding.UTF8);
// PROC 1 This opens entire file in memory and uses Replace and Regex Replace
text = text.Replace("</text>", "");
text = Regex.Replace(text, @"\<ref.*?\</ref\>", "");
File.WriteAllText(defTempProc1FileName, text);
// PROC 2 This reads file line by line and uses String.IndexOf and String.Substring and StringBuilder to build the new lines
using (var fileStream = File.OpenRead(defTempProc1FileName))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line, newdef;
while ((line = streamReader.ReadLine()) != null)
{
String[] arr = line.Split('\t');
string def = arr[2];
newdef = Util.ProcessDoubleBrackets(def);
File.AppendAllText(defTempProc2FileName, newdef + Environment.NewLine);
}
}
}
public static string ProcessDoubleBrackets(string def)
{
if (def.IndexOf("[[") < 0)
return def;
StringBuilder sb = new StringBuilder();
... Some processing
sb.Append(def.Substring(pos, i - pos));
... Some processing
return sb.ToString();
}
考虑这个意见,因为只有一个提示:如果您有Visual Studio中,您可以在该解决方案中的文件夹,并使用搜索和替换运气 – StackOrder