Kuy*_*aye 0 .net c# ini file edit
我找到了一些与编辑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);
}
Run Code Online (Sandbox Code Playgroud)
简单的方法是使用WritePrivateProfileString和GetPrivateProfileString功能的Kernel32.dll读取和写入INI文件.
例:
写给INI:
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
public static extern long WriteValueA(string strSection,
string strKeyName,
string strValue,
string strFilePath);
Run Code Online (Sandbox Code Playgroud)
用法:
WriteValueA("SectionToWrite", "KeyToWrite", "Value", @"D:\INIFile.ini");
Run Code Online (Sandbox Code Playgroud)
从INI阅读:
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
public static extern int GetKeyValueA(string strSection,
string strKeyName,
string strEmpty,
StringBuilder RetVal,
int nSize,
string strFilePath);
Run Code Online (Sandbox Code Playgroud)
用法:
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
Run Code Online (Sandbox Code Playgroud)