using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections; using System.Text.RegularExpressions; namespace PowerSwitcher { public class InIReader { private Dictionary> cont; private FileSystemWatcher k = new FileSystemWatcher(Directory.GetCurrentDirectory(), "*.ini"); private string filename; public InIReader(string filename) { this.filename = filename; k.Changed += new FileSystemEventHandler(this.readAgain); loadFile(); } private void readAgain(object sender, EventArgs e) { loadFile(); } private void loadFile() { this.cont = new Dictionary>(); StreamReader file = new StreamReader(this.filename); List buf = new List(); string fline = ""; while (fline != null) { fline = file.ReadLine(); if (fline != null) buf.Add(fline); } file.Close(); Dictionary sub = new Dictionary(); string cap = ""; foreach (string line in buf) { Match match = Regex.Match(line, @"^\[[a-zA-Z0-9\-_ ]+\]\w*$", RegexOptions.IgnoreCase); if (match.Success) { if (sub.Count != 0 && cap != "") { cont.Add(cap, sub); } cap = line; sub = new Dictionary(); } else { if (line != "" && cap != "") { string key = line.Substring(0,line.IndexOf('=')); string value = line.Substring(line.IndexOf('=')+1); sub.Add(key, value); } } } if (sub.Count != 0 && cap != "") { cont.Add(cap, sub); } } public List getSections() { return cont.Keys.ToList(); } public String getValue(String section, String key) { if (!section.StartsWith("[")) { section = "[" + section + "]"; } if (cont.Keys.Contains(section)) { if (cont[section].Keys.Contains(key)) { return cont[section][key]; } } return null; } public void SetValue(string section, string key, string value) { if (!section.StartsWith("[")) { section = "[" + section + "]"; } if (cont.Keys.Contains(section)) { if (cont[section].Keys.Contains(key)) { cont[section][key] = value; } else { cont[section].Add(key, value); } } else { Dictionary sub = new Dictionary(); sub.Add(key, value); cont.Add(section, sub); } k.Changed -= null; saveSettings(); loadFile(); k.Changed += new FileSystemEventHandler(this.readAgain); } private void saveSettings() { StreamWriter file = new StreamWriter(this.filename); file.BaseStream.SetLength(0); file.BaseStream.Flush(); file.BaseStream.Seek(0, SeekOrigin.Begin); foreach (KeyValuePair> cap in this.cont) { file.WriteLine(cap.Key); foreach (KeyValuePair sub in cap.Value) { file.WriteLine(sub.Key + "=" + sub.Value); } file.WriteLine(); } file.Flush(); file.Close(); } } }