csharp-s6geige
authorSparky6 <sparky6@core>
Sun, 2 Jul 2023 17:03:51 +0000 (19:03 +0200)
committerSparky6 <sparky6@core>
Sun, 2 Jul 2023 17:03:51 +0000 (19:03 +0200)
csharp/mutil/Configuration.cs [new file with mode: 0644]

diff --git a/csharp/mutil/Configuration.cs b/csharp/mutil/Configuration.cs
new file mode 100644 (file)
index 0000000..0036751
--- /dev/null
@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace mutil {
+
+public class Configuration {
+    private Dictionary<string,string> configs = new Dictionary<string,string>();
+    private string filename;
+    private Configuration(string filename) {
+        this.filename = filename;
+        if (File.Exists(filename)) {
+            XmlExtractor xmle = new XmlExtractor();
+            xmle.openInput(filename);
+            xmle.requireChild("configuration");
+            string elem;
+            string value;
+            Dictionary<string,string> attrs;
+
+            int ctl = xmle.extractElement(XmlExtractor.EC_BEG, out elem, out value, out attrs);
+            while (ctl != XmlExtractor.EC_END) {
+                if (elem != "entry") throw new ApplicationException("entry tag expected.");
+                configs.Add(attrs["key"], value);
+                ctl = xmle.extractElement(ctl, out elem, out value, out attrs);
+            }
+        }
+    }
+    static private Configuration theInstance = null;
+    static public Configuration getInstance(string filename) {
+        if (theInstance == null) theInstance = new Configuration(filename);
+        return theInstance;
+    }
+    static public Configuration getInstance() {
+        if (theInstance == null) throw new System.Exception("parameter filename missing.");
+        return theInstance;
+    }
+    
+    public void Add(string key, string value) {
+       string dummy;
+       if (this.configs.TryGetValue(key, out dummy)) this.configs[key] = value;
+       else this.configs.Add(key, value);
+    }
+    
+    public string Require(string key) {
+       return this.configs[key];
+    }
+
+    public string Get(string key) {
+       string value;
+       this.configs.TryGetValue(key, out value);
+       return value;
+    }
+
+    public string Get(string key, string defaut) {
+       string value;
+       if (! this.configs.TryGetValue(key, out value)) return defaut;
+       return value;
+    }
+
+    ~Configuration() {
+        StreamWriter outfile;
+        using ( outfile = new StreamWriter (this.filename)) {
+            outfile.WriteLine("<configuration>");
+            foreach(var config in this.configs) {
+                outfile.WriteLine("<entry key=\"{0}\">{1}</entry>", config.Key, config.Value);
+            }
+            outfile.WriteLine("</configuration>");
+        }    
+    }
+}
+
+}
+