如何修改文本文件中的多行?

How to modify multiple rows in a text file?

如果我在我的代码中输入下一条语句:

private void Install_Click(object sender, EventArgs e)
        {
var lin =File.ReadLines(path + "installer.ini").ToArray();
var license = lin.Select(line => Regex.Replace(line, @"license=.*", "license=yes"));
            File.WriteAllLines(installerfilename, license);
}

installer.ini 我将有 :license=yes。 但是,如果我添加另一个,,只有第二个可以工作。

private void Install_Click(object sender, EventArgs e)
            {
    var lin =File.ReadLines(path + "installer.ini").ToArray();
    var license = lin.Select(line => Regex.Replace(line, @"license=.*", "license=yes"));
                File.WriteAllLines(installerfilename, license);
 var lmgr_files = lin.Select(line => Regex.Replace(line, @"lmgr_files=.*", "lmgr_files=true"));
            File.WriteAllLines(installerfilename, lmgr_files);
    }

installer.ini 中保持 license=no 并且将是 lmgr_files=true 。 我如何才能使第二个代码起作用,但方法不起作用?

那是因为您正在读取文件一次,写入两次

首先,您正在编辑 license 行,写入编辑后的文件。然后您正在编辑 lmgr_files 行,覆盖您之前的编辑。

删除您对 File.WriteAllLines() 的第一个呼叫。在你的第二个 select 中,使用 license(即第一个 Select() 返回的内容)而不是 lin(即文件的原始内容)。

// Use Path.Combine() to combine path parts.
var lin = File.ReadLines(Path.Combine(path, "installer.ini")).ToArray();

// Replace the license=... part. License will now hold the edited file.
var license = lin.Select(line => Regex.Replace(line, @"license=.*", "license=yes"));

// No need to write the file here, as it will be overwritten.
//File.WriteAllLines(installerfilename, license);

// Select from the edited lines (i.e. "license").
var lmgr_files = license.Select(line => Regex.Replace(line, @"lmgr_files=.*", "lmgr_files=true"));

// Now it is time to write!
File.WriteAllLines(installerfilename, lmgr_files);

可选地,使用 different method 编辑 INI 文件。

你也可以在一个循环中完成。类似的东西:

       var lin = File.ReadLines(Path.Combine(path,"installer.ini")).ToArray();
       var license = lin.Select(line =>
       {
           line = Regex.Replace(line, @"license=.*", "license=yes");
           //you can simply add here more regex replacements
           //line = Regex.Replace(line, @"somethingElse=.*", "somethingElse=yes");

           return Regex.Replace(line, @"lmgr_files=.*", "lmgr_files=true");
       });

       File.WriteAllLines(installerfilename, license);