On 20/08/2008 in message
<0a**********************************@r15g2000prd. googlegroups.com>
CSharp-Jay wrote:
>So I have been programming in C# on a personal level as of lately, and
am curious about something. Lately I have been experimenting around
with file create/write, etc. I can open and read the whole file, but
how do I read specific words into my program? Like for example, I
have an ini file that my program writes to and needs to read from to
know user specific settings. But I need to know each line
individually and what the value is so that I can set that code to make
changes in my program. If this makes any sense lol :) Please help!
If you really want to use an ini file then you can use:
private string GetINIKeyValue(string sectionName, string keyName, string
iNIFilePath)
{
int apiResult = 0;
int bufferSize = 2048;
StringBuilder lpReturn = new StringBuilder(bufferSize);
apiResult = GetPrivateProfileString(sectionName, keyName, "", lpReturn,
bufferSize, iNIFilePath);
if (apiResult == 0)
{
return "";
}
return lpReturn.ToString();
}
private bool WriteINIKeyValue(string sectionName, string keyName, string
keyValue, string iniFilePath)
{
int apiResult = WritePrivateProfileString(sectionName, keyName,
keyValue, iniFilePath);
if (apiResult == 0)
return false;
else
return true;
}
Prototypes you need are:
// GetPrivateProfileString
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString",
SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileString(string lpSectionName,
string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int
nSize, string lpFileName);
// WritePrivateProfileString
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString",
SetLastError = true, CharSet = CharSet.Auto)]
public static extern int WritePrivateProfileString(string
lpApplicationName, string lpKeyName, string lpString, string lpFileName);
They will look odd in here but paste them in to your project files and
they will be ok. You will also need:
using System.Runtime.InteropServices;
As Peter has said ini files are old hat now, although MSFT has accepted
that separate configuration files may be better than using the Registry.
You probably ought to look at achieving the same effect using xml files
nowadays.
--
Jeff Gaines Damerham Hampshire UK
That's an amazing invention but who would ever want to use one of them?
(President Hayes speaking to Alexander Graham Bell on the invention of the
telephone)