编辑ini文件

本文关键字:文件 ini 编辑 | 更新日期: 2023-09-27 18:05:47

我发现一些代码可以完美地编辑ini文件的某个部分,但它只选择我想要编辑的行的第一个实例。我知道我可能只需要手动输入代码中的所有索引,从我想要开始编辑的地方开始,但知道事情是如何随着时间而变化的,ini文件可能会发生变化,索引也会发生变化。有人能解释一下这个问题吗?

const string FileName = "File.ini";
string file= File.ReadAllText(FileName);
const string Pattern = @"pattern = (?<Number>)";
Match match = Regex.Match(config, Pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
    int index = match.Groups["Number"].Index;
    string newText= **********;
    file = file.Remove(index, 21);
    file = file.Insert(index, newText);
    File.WriteAllText(FileName, file);
}  

编辑ini文件

简单的方法是使用Kernel32.dllWritePrivateProfileStringGetPrivateProfileString函数来读写INI文件

的例子:

For Writing to INI:

[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
public static extern long WriteValueA(string strSection, 
                                       string strKeyName, 
                                       string strValue, 
                                       string strFilePath);

用法:

 WriteValueA("SectionToWrite", "KeyToWrite", "Value", @"D:'INIFile.ini");

from INI:

[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
public static extern int GetKeyValueA(string strSection, 
                                      string strKeyName, 
                                      string strEmpty, 
                                      StringBuilder RetVal, 
                                      int nSize, 
                                      string strFilePath);

用法:

StringBuilder temp = new StringBuilder(255);
int i = GetKeyValueA("TargetSection", "KeyToRead", string.Empty, temp, 255, @"D:'INIFile.ini");
string sValue = temp.ToString(); //desired value of the key

可能与为什么只有一个匹配的问题无关,但请注意,在此regex的情况下:

const string Pattern = @"pattern = (?<Number>)";

号码组将包含空字符串。您可能需要:

const string Pattern = @"pattern = (?<Number>'d+)";

查看测试结果

http://regex101.com/r/aT1aT0