3

My ini file does not have any section. It has following data

com.ibm.rcp.toolbox.admin/toolboxvisibleChild=false
com.ibm.collaboration.realtime.community/defaultAuthType=ST-DOMINO-SSO
com.ibm.collaboration.realtime.brokerbridge/startBroker=false
com.ibm.collaboration.realtime.webapi/startWebContainer=true

I want to use function.

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
             string key,string def, StringBuilder retVal,
        int size,string filePath);

My problems

  1. I cannot give section name in the function because I dont have any
  2. If I give section name null, it returns nothing
  3. I don't want to use brute force like ReadAllText
om471987
  • 5,398
  • 5
  • 32
  • 40
  • What happens if you pass in a blank string for the section name instead of null? – Marcus Mar 13 '12 at 14:45
  • What is GetPrivateProfileString, is that an external library? – MattDavey Mar 13 '12 at 14:49
  • 1
    GetPrivateProfileString & WritePrivateProfileString will not work on files that aren't formatted like .ini files - i.e., missing [section]. 'null' doesn't mean 'no section'. It says right here in the documentation. http://msdn.microsoft.com/en-us/library/windows/desktop/ms724353%28v=vs.85%29.aspx If you want to consume this format, I think you may have to write your own parser (doesn't seem so bad to me) or find open-source code that does it already. P.S. GetPrivateProfileString is the old Windows API for reading INI files (@MattDavey). – Val Akkapeddi Mar 13 '12 at 14:51
  • I know you said you don't want to "brute force" it, but...can you just split each line on `=`, the left side being the name and the right side being the value? If you know your .ini file will never have any sections and there aren't issues like quoting or escaped equal signs to deal with, that should be really easy. `GetPrivateProfileString` might not do what you want, since it doesn't seem to accept `null` or `string.Empty`. – Lance U. Matthews Mar 13 '12 at 14:52

2 Answers2

3

Using File.ReadLines and some LINQ is actually not that bad:

var dict = File.ReadLines("config.txt")
               .Where(line => !string.IsNullOrWhiteSpace(line))
               .Select(line => line.Split(new char[] { '=' }, 2, 0))
               .ToDictionary(parts => parts[0], parts => parts[1]);

var result = dict["com.ibm.rcp.toolbox.admin/toolboxvisibleChild"];
TaW
  • 53,122
  • 8
  • 69
  • 111
dtb
  • 213,145
  • 36
  • 401
  • 431
2

Here's a library that the author says supports section-less keys. I myself have not tried this library.
Or, you could simply edit the Ini file and add in a "header"/section name right at the top, then delete it once you're done reading.

Marcus
  • 5,407
  • 3
  • 31
  • 54
  • 1
    Finally, my conclusion is sectionless ini are not supported by win32. So its better to use filereader mentioned by dtb... – om471987 Mar 16 '12 at 21:14