Home > Enterprise >  Read and Write INI file without sections
Read and Write INI file without sections

Time:10-10

There is an ini file format

########## Order section ##########
KeyOne=Value1
....
....
....
...
KeyMore=999
Key = 88888*
......
......
......

how can I edit what is behind the = ? I tried in many ways, but since there are no sections in the ini file, I can’t figure out how to change the values Value1 and 999 and 88888*?

Tried splitting strings with split "=" , but failed to change values. and also add new lines to the file? after Key = 88888*

1.If there are spaces or text in the textbox, then it does not work.

const string filepath = @"C:\Users\123\Desktop\Config.ini";
string text = File.ReadAllText(filepath);

const string PATTERN = @"KeyOne=(?<Number>[\d\.] )";
Match match = Regex.Match(text, PATTERN, RegexOptions.IgnoreCase);
if (match.Success)
{
   int index = match.Groups["Number"].Index;
   int length = match.Groups["Number"].Length;

   text = text.Remove(index, length);
   text = text.Insert(index, Program.form1.textBox11.Text);

   File.WriteAllText(filepath, text);
}

CodePudding user response:

An INI file has a well defined structure composed by one or many [Sections] and zero or many pairs of [Key]=[Value] under each section. A file without at least a section is not a proper INI file and the standard windows API GetPrivateProfileString and WritePrivateProfileString are not able to read a file with that format.

However, your file is a lot simpler than a standard INI file. It is just composed by pairs of [Key]=[Value] so it is a naturally perfect fit for a Dictionary<string, string>

Reading it coud be simple as

Dictionary<string, string> GetConfigData(string fileName)
{
    Dictionary<string, string> data = new Dictionary<string, string>();
    foreach (string line in File.ReadLines(fileName))
    {
        var lineData = line.Split('=');
        data.Add(lineData[0], lineData[1]);
    }
    return data;
}

and writing back that dictionary is even simpler

void WriteConfigData(string fileName, Dictionary<string, string> data)
{
    File.WriteAllLines(fileName, data.Select(z => $"{z.Key}={z.Value}{Environment.NewLine}"));
}
 

Now if you want to change some value you could have

var data = GetConfigData("yourbadinifile.ini");
data["KeyValue"] = "a new value";
WriteConfigData("yourbadinifile.ini", data);

Warning: In the examples above there is no error checking. A robust solution should check if the file passed to the read method exists and if the split operation produces an array of two elements. Consider also that checking for binary files is also an unhandled problem and with complex solutions. So we could also consider to let exceptions bubble up to the client caller.

  • Related