Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


A Simple .ini File Reader/Writer
Note: Depending on what you need, it may be a lot simpler to just use the Windows INI read/write utilities:

[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);

However, if you'd rather not, here's a dirt simple class to save and load your variables from an .ini file.
Just instantiate the class, Write some variables, and call Save. Calling Read will retrieve your variables the next time that you need them. You'll need to save a file name (SettingsPath) to specify where to save the .ini file.


///
/// Read/write to a very simple .ini file
///
public class MyIni{
public Hashtable ht;
string SettingsPath = "C:\MyIniFile.ini";

public MyIni()
{
ht = new Hashtable(10);
this.Load();
}
public void Write(CfgFields field, string val)
{
Write(field.ToString(), val);
}
public void Write(string field, string val)
{
this.ht[field] = val;
}
public string Read(CfgFields field)
{
return Read(field.ToString());
}
public string Read(string field)
{
if(this.ht[field] == null)
return "";
else return this.ht[field].ToString();
}
///
/// Load data from .ini file to this class
///
public void Load()
{
ht.Clear();
System.IO.StreamReader r = null;
try
{
r = System.IO.File.OpenText(SettingsPath);
string line = r.ReadLine();
while(line != null)
{
int i = line.IndexOf("=");
ht.Add(line.Substring(0,i),line.Substring(i+1));
line = r.ReadLine();
}
}
catch{}
finally
{
if(r != null)
r.Close();
}
} // LOAD
///
/// Save data from this class to .ini file
///
public void Save()
{
StreamWriter w = null;
try
{
w = System.IO.File.CreateText(SettingsPath);
foreach(object o in this.ht.Keys)
{
string val = this.ht[o.ToString()].ToString();
w.WriteLine(o.ToString() + "=" + val);
}
}
catch{}
finally
{
if(w != null)
w.Close();
}
} // SAVE

} // class

/// Save your variable names here for easier access!
public enum CfgFields
{
AVARIABLEA,
BVARIABLEB,
CVARIABLEC,
DVARIABLED
}

Created By: amos 3/20/2006 12:12:59 AM