1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
namespace test
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Button1Click(object sender, EventArgs e)
{
ItemConfig<bool> item = new ItemConfig<bool>();
item.Valeur = false;
item.Defaut = false;
ItemConfig<int> item1 = new ItemConfig<int>();
item1.Valeur = 0;
item1.Defaut = 10;
CfgSection sec = new CfgSection("name");
sec.Add(item);
CfgSection sec1 = new CfgSection("name");
sec1.Add(item);
AppConfig cfg = new AppConfig();
cfg.AddSection(sec);
cfg.AddSection(sec1);
string Path = Application.StartupPath;
Path = System.IO.Path.Combine(Path, "ConfigFile.xml");
Sauver.WriteDatasToFile(cfg, Path);
}
}
public interface IItemConfig{}
[Serializable]
public class ItemConfig<T> : IItemConfig
{
public T Valeur{
get;
set;
}
[XmlAttribute]
public T Defaut{
get;
set;
}
public ItemConfig()
{ }
}
[Serializable]
public class CfgSection
{
private string _sectionName = "";
private IList<IItemConfig> _lst = new List<IItemConfig>();
[XmlAttribute]
public string Name{
get { return _sectionName; }
set { _sectionName = value; }
}
public IList<IItemConfig> Items{
get { return _lst; }
set {_lst = value; }
}
public CfgSection()
{}
public CfgSection(string name)
{
_sectionName = name;
}
public void Add(IItemConfig item)
{
_lst.Add(item);
}
}
[ Serializable ]
public class AppConfig
{
private string _file = "";
private List<CfgSection> _sections = new List<CfgSection>();
public string FichierConfig
{
get { return _file; }
}
public List<CfgSection> Sections
{
get { return _sections; }
set { _sections = value; }
}
public AppConfig()
{}
public void AddSection(CfgSection section)
{
_sections.Add(section);
}
}
public static class Sauver
{
public static bool WriteDatasToFile<T>(T obj, string fileName)
{
bool ret;
StreamWriter wr = null;
try
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (wr = new StreamWriter(fileName))
{
xs.Serialize(wr, obj);
ret = true;
}
}
catch (Exception e) {
System.Windows.Forms.MessageBox.Show(e.Message);
ret = false; }
return ret;
}
}
} |
Partager