|
This is much simpler than other INI readers I have encountered.
In my program, I have this:
bool myBool;
IniFile myIni = new IniFile((AppDomain.CurrentDomain.BaseDirectory) + "Planet_001.ini");
int CurrentSeed;
myBool = int.TryParse(myIni.IniReadValue("Init", "CurrentSeed"), out CurrentSeed);
if (myBool == false)
{
CurrentSeed = 0;
myIni.IniWriteValue("Init", "CurrentSeed", " 0");
myBool = true;
}
This tests the value in the INI, and if absent or of the wrong type, will substitute a default value, and write that value to the INI file as well. It also will create an INI file if none exists.
|
|
|
|
|
Replace DLLImport("kernel32")] for [DLLImport("KERNEL32.DLL")]
But, I Approve.
PT_BR:
Substitua a linha [DLLImport("kernel32")] por [DLLImport("KERNEL32.DLL")]
Mas, Eu Aprovo
|
|
|
|
|
|
Thank you for posting this! I am not able to append an existing file, it just overwrites. Any suggestions, anyone?
|
|
|
|
|
Thanks.. Helped me at the right time
|
|
|
|
|
|
my long time issue of saving config solved
|
|
|
|
|
for me it dont work on Windows 8 the Program don't create the ini file
|
|
|
|
|
i am using windows 7. please check the file path . use absolute path like @c:\temp.ini. if you put only file name then it's not creating ini file.
|
|
|
|
|
The Closing event is obsolete in the .NET Framework version 2.0; use the FormClosing event in example instead.
|
|
|
|
|
this is awesome..very comprehensive...thanks...
and easy to use..Cheers!
|
|
|
|
|
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
public class IniFile
{
[DllImport("KERNEL32.DLL", EntryPoint = "GetPrivateProfileStringW",
SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int GetPrivateProfileString(
string lpSection,
string lpKey,
string lpDefault,
StringBuilder lpReturnString,
int nSize,
string lpFileName);
[DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW",
SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int WritePrivateProfileString(
string lpSection,
string lpKey,
string lpValue,
string lpFileName);
private string _path = "";
public string Path {
get
{
return _path;
}
set
{
if (!File.Exists(value))
File.WriteAllText(value, "", Encoding.Unicode);
_path = value;
}
}
public IniFile(string INIPath)
{
this.Path = INIPath;
}
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.Path);
}
public string IniReadValue(string Section, string Key)
{
const int MAX_CHARS = 1023;
StringBuilder result = new StringBuilder(MAX_CHARS);
GetPrivateProfileString(Section, Key, "", result, MAX_CHARS, this.Path);
return result.ToString();
}
}
|
|
|
|
|
Clear structured an easy to use!
|
|
|
|
|
Thankx Dear...!!! It helps me lot...!!!
But i hav one query....if i want to use <> this for defining Section i.e.
how to read this test.ini file?
<info>
<mdbpath>=<d:\fff\xyz.mdb>
|
|
|
|
|
|
My piece of code in VB.Net
<Runtime.InteropServices.DllImport("kernel32.dll", CharSet:=Runtime.InteropServices.CharSet.Ansi, SetLastError:=True)> _
Private Function WritePrivateProfileString(Section As String, Key As String, Value As String, FilePath As String) As Long
End Function
<Runtime.InteropServices.DllImport("kernel32.dll", CharSet:=Runtime.InteropServices.CharSet.Ansi, SetLastError:=True)> _
Private Function GetPrivateProfileString(Section As String, Key As String, DefaultValue As String, Result As System.Text.StringBuilder, Size As Integer, FilePath As String) As Long
End Function
Public Function IniFileModifyValue(ByVal FilePath As String, ByVal Section As String, ByVal Key As String, ByVal Value As String) As Boolean
Dim ret As Long
Try
ret = WritePrivateProfileString(Section, Key, Value, FilePath)
If ret = 0 Then Return False
Catch ex As Exception
Return False
End Try
Return True
End Function
Public Function IniFileReadSingleValue(FilePath As String, Section As String, Key As String, DefaultValue As String) As String
Dim ret As Long
Dim res As String = DefaultValue
Dim sb As New System.Text.StringBuilder(255)
If IO.File.Exists(FilePath) = True Then
ret = GetPrivateProfileString(Section, Key, DefaultValue, sb, sb.Capacity, FilePath)
If ret > 0 Then
ret = Global.System.Math.Min(ret, sb.Capacity)
ret = Global.System.Math.Min(ret, sb.Length)
res = sb.ToString(0, ret)
End If
End If
Return res
End Function
|
|
|
|
|
|
It solved my problem and useful article..
|
|
|
|
|
It solved my problem and useful article..
|
|
|
|
|
this Cod is perfect .. Thx a lot
|
|
|
|
|
|
|
///
/// see IniWriteValue, but write an integer
///
public void IniWriteInt(string section, string key, int value)
{
String s = Convert.ToString(value);
IniWriteValue(section, key, s);
}
///
/// see IniReadValue, but read as an integer.
///
public int IniReadInt(string section, string key)
{
String s= IniReadValue(section,key);
String exceptionMsg = "string could not be converted to an int";
int value;
try
{
value = Convert.ToInt32(s);
}
catch (FormatException ex)
{
throw new IniFileException(exceptionMsg, ex);
}
catch (OverflowException ex)
{
throw new IniFileException(exceptionMsg, ex);
}
return value;
}
public class IniFileException : Exception
{
//TODO put this class in it's own file.
public IniFileException(String message)
: base(message)
{
}
public IniFileException(string message, Exception ex)
: base(message, ex)
{
}
}
|
|
|
|
|
This is way overcomplicated. Try this instead:
public class IniFile
{
public string path;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public IniFile(string INIPath)
{
path = INIPath;
}
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.path);
}
public string IniReadValue(string Section,string Key, string Def)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, (def != null ? def : string.Empty), temp, 255, this.path);
return temp.ToString();
}
public void IniWriteValue(string Section, string Key, int Value)
{
IniWriteValue(Section, Key, Value.ToString());
}
public int IniReadValue(string section, string key, int? def)
{
string s = ReadValue(section, key, (def != null ? def.ToString() : null));
int i = 0;
if (int.TryParse(s, out i))
return i;
else
throw new IniFileException("Tried to retrieve invalid value type from ini.");
}
}
public class IniFileException : Exception
{
public IniFileException(string Message)
: base(Message)
{
}
}
Your stack trace will now have everything you need, and you can get rid of the messy try...catch...throw. There's no need to include an InnerException as part of the newly thrown IniFileException, as no other Exception has been generated yet.
You have room for a default value now, and you're using overloads instead of multiple alternately named, similar functions. This is a more standardized method for this sort of endeavor.
An int.TryParse is just a hair slower than a Convert.ToInt32 but the overhead this method will save you on failure is well worth it. Additionally, it's the preferred method for conversion.
|
|
|
|
|
Hi md5sum, thx for your insight here!
Allthough the methodes I posted
do what they supposed to, I agree
with overloading, the methods you posted.
I made changes accordingly. However I am not sure
about using tryparse. if reading from ini would fail because
the number is too high to be parsed or there is an invalid
format, then you can't distinqush between those cases from
iniexception anymore.
|
|
|
|
|