I am dealing with an application that still uses INI files for configuration. I wanted to make a temporary change to an INI file, but the result was not what I expected.
Let's say the original INI file is
[mysection]
mykey=myvalue
and I wanted to make a revertable change for testing purposes. From my (maybe incomplete or wrong) memories, I recalled that a lot of programs used batch files to modify INI files like so:
echo [mysection]>>test.ini
echo mykey=anothervalue>>test.ini
resulting in an INI file like
[mysection]
mykey=myvalue
[mysection]
mykey=anothervalue
The "revertable" part of this would be that I could simply delete the last 2 lines.
I don't recall any utilities which would have taken care about duplicate sections or keys. Obviously, "echoing" the section is needed to make sure that the section exists in case it did not exist before.
For the last 30 years or so, I believed that the last entry of an INI file wins, exactly for the reason to support these "echoing" changes.
Now, as I said, this change did not work out for the application I am using today. My first thought was that they used an incompatible INI file parser. So I conducted the following test myself, just relying on the Windows API:
// C#
static void Main()
{
var sb = new StringBuilder(500);
GetPrivateProfileString(
"mysection", "mykey","", sb, (uint)sb.Capacity, "e:\\test.ini");
if (sb.ToString() != "anothervalue")
throw new ApplicationException("Not what I expected");
}
Guess what: the result is not what I expected.
Could someone confirm (or disprove) that I was wrong for 30 years? Did Windows 3.x and Windows 95 consider the first section and first key of INI files only?
(I am only interested in the "official" way of reading INI files using the Windows API GetPrivateProfileString()
)
GetPrivateProfileString
.echo [mysection]>>test.ini
may not do what you expect. If you have a file namedm
(ory
,s
,e
,c
, ...etc...) in your current directory, for example,[mysection]
can be treated as a glob expansion matching that filename, and thus write only the name of said file instead of the string[mysection]
. Quoting it asecho "[mysection]"
will prevent this.