Using GetPrivateProfileSection() method in C#

Dear friends

i am trying to read .INI file using c#.

istead of StreamReader() i need to use GetPrivateProfileSection() to get the values of a specified section.

i am getting exceptions while using the method.

it will be great if any suggetions on syntax of GetPrivateProfileSection() method in C#

and how to do that.

thanks

ranadheer.



Answer this question

Using GetPrivateProfileSection() method in C#

  • harkat1

    The GetPrivateProfileSection function retrieves all the keys and values for the specified section of an initialization file.

    Reference to http://msdn2.microsoft.com/en-us/library/ms724363.aspx

    Hope it helps



  • Suganya Mahadevan

    yo Figo,
    The question was asked as to how to use it in C# and not windows sdk

    try this instead

    [DllImport("kernel32", SetLastError = true)]
    private static extern int GetPrivateProfileString(
    string sectionName,
    string keyName,
    string defaultValue,
    byte[] iniValue,
    int bufferLen,
    string filename
    );

    public string getString(string iniFilename, string section, string key, string defaultValue)
    {
    string retValue = defaultValue;
    try
    {
    // prepare the default return and create a byte array to pass as a pointer

    byte[] bRet = new byte[255];

    // call the API function, passing a Section name, value name, default
    // value, buffer length (length of the passed byte array) and the ini
    // filename.
    int i = GetPrivateProfileString(section, key, defaultValue, bRet, 255, iniFilename);

    // as referred above we use a framework function to collect the string
    // from the byte array used as a pointer. Note the 'i' variable is the
    // return from the API call, this is passed to the text encoding as the
    // total length of the return.
    retValue = System.Text.Encoding.GetEncoding(1252).GetString(bRet, 0, i).TrimEnd((char)0);
    }
    catch (FileNotFoundException)
    {
    MessageBox.Show(" Ini file path undefined ");
    }
    return retValue;

    }

  • Using GetPrivateProfileSection() method in C#