批量替换文本文件中的多个字符串的最佳方法是什么

本文关键字:字符串 最佳 方法 是什么 替换 文本 文件 | 更新日期: 2023-09-27 18:33:02

我有一个文件,它有很多字符串和许多替换,我想用它们的替换替换字符串,然后保存文本文件,这是我尝试过的,虽然做得不好:

StreamReader sr = new StreamReader(fullPath + "''DICT_J.txt", Encoding.Unicode);
            string cdID;
            string str;
            while (sr.Peek() >= 0)
            {
                string[] temp = sr.ReadLine().Split('^');
                if (temp.Length == 3)
                {
                    cdID = temp[1];
                    str = temp[2];
                    File.WriteAllText(path, Regex.Replace(File.ReadAllText(path), str, cdID), Encoding.Unicode);
                }
            }
            sr.Close();
            sr.Dispose();

这里(对不起,我无法在这里发布它,因为 SOF 不允许行返回)是包含替换的文件的示例,这是模板:行 ID^替换^要替换的字符串

批量替换文本文件中的多个字符串的最佳方法是什么

不确定这是否有帮助,但这些是我的猜测。这些方法还有其他编码重载,我在这里没有使用,但在您的情况下可能有用。

1.将原始文件上的字符串替换为替换文件中的LineID

public void Replace(string originalFile, string replacementsFile)
{
    var originalContent = System.IO.File.ReadAllLines(originalFile);
    var replacements = System.IO.File.ReadAllLines(replacementsFile);
    foreach(var replacement in replacements)
    {
        var _split = replacement.Split(new char[] { '^' });
        var lineNumber = Int32.Parse(_split[0]);
        // checks if the original content file has that line number and replaces
        if (originalContent.Length < lineNumber)
            originalContent[lineNumber] = originalContent[lineNumber].Replace(_split[1], _split[2]);
    }
    System.IO.File.WriteAllLines(originalFile, originalContent);
}

2. 替换另一个文件上替换模板的每个匹配项

public void Replace(string originalFile, string replacementsFile)
{
    var originalContent = System.IO.File.ReadAllText(originalFile);
    var replacements = System.IO.File.ReadAllLines(replacementsFile);
    foreach(var replacement in replacements)
    {
        var _split = replacement.Split(new char[] { '^' });
        originalContent = originalContent.Replace(_split[1], _split[2]);
    }
    System.IO.File.WriteAllText(originalFile, originalContent);
}