KuyaBraye
KuyaBraye

Reputation: 65

Editing an ini file

I found some code that works perfectly with editing a certain section of an ini file, but it only picks up the first instance of the line that I want to edit. I know I can probably just manually input all the indexes in the code from where I want to start the editing, but knowing how things can change over time there might be changes to the ini file and then the indexes will change as well. Can someone shed some light to this issue?

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

Upvotes: 0

Views: 2800

Answers (2)

Hassan
Hassan

Reputation: 5430

Easy way is to use WritePrivateProfileString and GetPrivateProfileString functions of Kernel32.dll for reading and writing into INI file.

Example:

For Writing to INI:

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

Usage:

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

For Reading from INI:

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

Usage:

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

Upvotes: 6

user3613916
user3613916

Reputation: 232

Probably unrelated to question of why only one match, but note that in case of this regex:

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

Number group will contain an empty string. You probably want:

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

See test results here

http://regex101.com/r/aT1aT0

Upvotes: 1

Related Questions