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

时间:2015-09-23 11:20:57

标签: c# visual-studio-2012 ini

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

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 {p>我将: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=nolmgr_files=true。 如何使第二个代码工作,并且方式不起作用?

2 个答案:

答案 0 :(得分:1)

这是因为您正在阅读文件一次,将其写为两次

首先编辑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文件。

答案 1 :(得分:1)

您也可以在一个循环中完成。这样的事情:

       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);