In my C# application, I wish to update the values in an INI file.
I used the interop services and wish to use the function WritePrivateProfileString
.
So I imported the DLL like this:
[DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW",
SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFilename);`
And used it in my function like this:
int result = WritePrivateProfileString(category, key, value, iniFile);
But the result is 0 and the INI file is not updated. How can I check the error?
Call the .NET equivalents to Win32 API functions GetLastError
and FormatMessage
, and the system will tell you why it's not letting you do this.
Cody is probably right in guessing that it is related to UAC, but without knowledge of where you are trying to write this file, we can only guess.
Update
As has been explained to me in the comments, Marshal.GetLastWin32Error
is the .NET way to get hold of the error code rather than calling GetLastError
directly. Calling GetLastError
directly will return the error code of the latest call to the Win32 API, which is likely to have been from a .NET runtime call to Win32 rather than your P/Invoke.