Search code examples
c#ini

GetPrivateProfileString without remove quotes


I have a ini file content below:

[Test]
Item="123","456"

I use the code below to parse the value.

But I found it didn't return the value I expected.

Seems like the function will auto remove first and last quote.

Any solution to fix this?

StringBuilder stringBuilder = new StringBuilder(500);
WINAPI.GetPrivateProfileString("Test", "Item", "", stringBuilder,500, "D:\\Test.ini");
var _value = stringBuilder.ToString(0, stringBuilder.Length); //get 123","456 instead "123","456"

Solution

  • It seems that even 2011 people tried to stay away from GetPrivateProfileString and it's oddities: What is the purpose of GetPrivateProfileString?

    So maybe you should store your application configuration somewhere else, for example an app.config file or the registry. Or you could simply read it with custom code:

    public static string? GetIniValue(string iniPath, string sectionName, string key)
    {
        if (!File.Exists(iniPath))
        {
            return null;
        }
    
        string sectionHeader = $"[{sectionName}]";
        return File.ReadLines(iniPath)
            .SkipWhile(l => !l.Equals(sectionHeader, StringComparison.InvariantCultureIgnoreCase))
            .Skip(1) // skip header
            .TakeWhile(l => l.Contains('='))
            .Select(GetMatchingKeyValueOrNull)
            .FirstOrDefault(value => value != null);
    
        string? GetMatchingKeyValueOrNull(string line)
        {
            string[] arr = line.Split('=');
            return arr.Length > 1 && arr[0].Trim().Equals(key, StringComparison.InvariantCultureIgnoreCase)
                ? arr[1].Trim() : null;
        }
    }
    

    string testItemValue = GetIniValue(@"D:\\Test.ini", "Test", "Item");