Laden...

Config-File Class

Erstellt von Xzelsius vor 13 Jahren Letzter Beitrag vor 13 Jahren 4.399 Views
X
Xzelsius Themenstarter:in
92 Beiträge seit 2008
vor 13 Jahren
Config-File Class

Beschreibung:

Einfache Klasse zum schreiben und lesen von "Config" Files. Idee dahinter ist die Variante mit *.ini Dateien.

Ich hab kurzerhand was eigenes geschrieben und hoffe irgendwer hier kann daraus was nehmen oder braucht es mal. Es ist sicherlich verbesserungsbedürftig, jedoch hab ich das so neben bei gemacht.


#region Klass: ConfigFile
/// <summary>
/// Config file class
/// </summary>
public class ConfigFile
{
#region Members
/// <summary>
/// File path
/// </summary>
private String m_Path;

/// <summary>
/// Property table
/// </summary>
private Hashtable m_Properties;
#endregion

#region Constructor
/// <summary>
/// Creates a new ConfigFile instance
/// </summary>
public ConfigFile()
{
this.m_Path = String.Empty;
this.m_Properties = new Hashtable();
}
#endregion

#region Functions

#region Load
/// <summary>
/// Loads the config file from the specific path
/// </summary>
/// <param name="path">File path</param>
public void Load(String path)
{
try
{
// Check for file
if (!File.Exists(path))
throw new Exception("File does not exist! " + path);

// Save file path
this.m_Path = path;

// Creates xml document
XmlDocument xmlDoc = new XmlDocument();

// Loads xml from file
xmlDoc.Load(path);

// Settingselement
XmlElement rootElement = xmlDoc["Settings"];

// Delete property list
this.m_Properties.Clear();

// Reads all elements
foreach (XmlNode node in rootElement.ChildNodes)
{
// Adds property
this.m_Properties.Add(node.Name, node.InnerText);
}
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region ReLoad
/// <summary>
/// Reloads the config file
/// </summary>
public void ReLoad()
{
try
{
if (this.m_Path != String.Empty)
{
this.Load(this.m_Path);
}
else
throw new Exception("No valid file path found!";);
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region Save
/// <summary>
/// Saves the config file
/// </summary>
public void Save()
{
try
{
if (this.m_Path != String.Empty)
{
this.Save(this.m_Path);
}
else
throw new Exception("No valid file path found!";);
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region Save(path)
/// <summary>
/// Saves the config file to the specific path
/// </summary>
/// <param name="path">File path</param>
public void Save(String path)
{
try
{
// Creates xml document
XmlDocument xmlDoc = new XmlDocument();

// Creats declaration node
XmlNode declNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "";);
xmlDoc.AppendChild(declNode);

// Settingselement
XmlElement rootElement = xmlDoc.CreateElement("", "Settings", "";);
xmlDoc.AppendChild(rootElement);

// Creates the Elements
foreach (String key in this.m_Properties.Keys)
{
// Creates the single Element
XmlElement appendElement = xmlDoc.CreateElement("", key, "";);
appendElement.InnerText = this.m_Properties[key].ToString();

// Add to document
xmlDoc["Settings"].AppendChild(appendElement);
}

// Save it
xmlDoc.Save(path);

// Save file path
this.m_Path = path;
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region AddProperty
/// <summary>
/// Adds an property
/// </summary>
/// <param name="name">Name</param>
public void AddProperty(String name)
{
try
{
// Check Var
Boolean bExists = false;

// Check if allreaddy exists
foreach (String key in this.m_Properties.Keys)
if (key == name)
bExists = true;

if (!bExists)
{
// Add property with null object
this.m_Properties.Add(name, null);
}
else
throw new Exception("Property " + name + " allready exist!";);
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region RemoveProperty
/// <summary>
/// Removes an property
/// </summary>
/// <param name="name">Name</param>
public void RemoveProperty(String name)
{
try
{
// Check Var
Boolean bExists = false;

// Check if allreaddy exists
foreach (String key in this.m_Properties.Keys)
if (key == name)
bExists = true;

if (bExists)
{
// Remove property
this.m_Properties.Remove(name);
}
else
throw new Exception("Property " + name + " does not exist!";);
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region SetPropertyValue
/// <summary>
/// Sets the value of an property
/// </summary>
/// <param name="name">Property name</param>
/// <param name="value">Value</param>
public void SetPropertyValue(String name, String value)
{
try
{
// Check Var
Boolean bExists = false;

// Check if allreaddy exists
foreach (String key in this.m_Properties.Keys)
if (key == name)
bExists = true;

if (bExists)
{
// Set property value
this.m_Properties[name] = value;
}
else
throw new Exception("Property " + name + " does not exist!";);
}
catch (Exception ex)
{
// TODO
}
}
#endregion

#region GetPropertyValue
/// <summary>
/// Gets the value of an property
/// </summary>
/// <param name="name">Property name</param>
/// <returns>Value</returns>
public String GetPropertyValue(String name)
{
try
{
// Check Var
Boolean bExists = false;

// Check if allreaddy exists
foreach (String key in this.m_Properties.Keys)
if (key == name)
bExists = true;

if (bExists)
{
// Return property value
return this.m_Properties[name].ToString();
}
else
throw new Exception("Property " + name + " does not exist!";);
}
catch (Exception ex)
{
// TODO
}

return String.Empty;
}
#endregion

#endregion
}
#endregion

Hier noch wie man es gebrauchen kann:


ConfigFile conf = new ConfigFile();

conf.AddProperty("SourcePath";);
conf.AddProperty("TargetPath";);
conf.AddProperty("Intervall";);

conf.SetPropertyValue("SourcePath", @"C:\Temp\Source";);
conf.SetPropertyValue("TargetPath", @"C:\Temp\Target";);
conf.SetPropertyValue("Intervall", "10";);

conf.Save(@"C:\Temp\settings.ini";);

Greets und Have fun 😃

[Edit]

  1. Sorry für die #region
  2. TODO = Error Handling !

Schlagwörter: Config, File, INI, Settings

public Knowledge Learn_CSharp();

1.373 Beiträge seit 2004
vor 13 Jahren

Hm, da sind aber schon ein paar schräge Sachen drin. Hier einige Beispiele:

  1. Der Code enthält diverse Syntaxfehler. Hast du ihn mal bei dir kompiliert?


foreach (string key in m_Properties.Keys)
        if (key == name)
          bExists = true;

m_Properties ist eine Hashtable, warum nicht einfach


bExists = m_Properties.ContainsKey(name);

Überhaupt machst du Dinge, die dir die Hashtable bereits abnimmt.

  1. Nimm statt einer Hashtable lieber ein Dictionary<string, string>, das hat noch einige Extrakniffe. Zum Beispiel kannst du deine RemoveProperty Methode umschreiben zu:

if(!m_Properties.Remove(name))
{
  throw new Exception("Property " + name + " does not exist!");
}

GetProperty wird zu:


string result;
if(!m_Properties.TryGetValue(name, out result))
{
  throw new Exception("Property " + name + " does not exist!");
}
    
return result;

SetPropertyValue ist ein einfaches


m_Properties[name] = value;

Und so weiter...
3. Es ist eine ganz schlechte Idee, Exceptions zu verschlucken.

  1. Warum muss ich eine Property erst hinzufügen, bevor ich ihren Wert setzen kann?

  2. Du hast sehr viel Duplikation in deinem Code, das ist nicht empfehlenswert.

  3. Ich bin ein Freak: ich möchte gerne Properites namens "<>foobar" speichern. Deine Klasse streikt hierbei und hilft mir auch nicht, den Fehler zu erkennen.

  4. Weg mit den ganzen sinnlosen Kommentaren!


// Creates xml document // <-- vollkommen überflüssig
XmlDocument xmlDoc = new XmlDocument();

X
Xzelsius Themenstarter:in
92 Beiträge seit 2008
vor 13 Jahren

=) Danke erstmal 😃

Naja wie gesagt, wurde nebenbei errichtet. Ich programmiere seit 1.5 Jahren und das nicht im grossen Stil. Danke für die Inputs! Werde es nun soweit anpassen damits bisschen besser läuft 😃

public Knowledge Learn_CSharp();