config文件操作类

1 public class AppConfig : AppSettingsReader
2 {
3 private string docName = string.Empty;
4
5
6 // Singleton fun.
7   private static AppConfig instance;
8 static AppConfig() { instance = new AppConfig(); }
9 private AppConfig()
10 : base()
11 {
12 docName = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Assembly.GetEntryAssembly().GetName().Name + ".exe.config");
13 }
14
15
16 /// <summary>Gets the current AppConfig instance.</summary>
17   static public AppConfig Instance
18 {
19 get { return instance; }
20 }
21
22
23 /// <summary>Gets the value for a specified key from the AppSettings property and returns an object
24 /// of the specified type containing the value from the .config file.</summary>
25 /// <param name="key">The key for which to get the value.</param>
26 /// <param name="type">The type of the object to return.</param>
27 /// <param name="defaultValue">The value to return if the specified key cannot be found.</param>
28 /// <returns>The value of the specified key.</returns>
29 /// <remarks>If the key is not found, then the value provided in defaultValue is returned.</remarks>
30 public object GetValue(string key, Type type, object defaultValue)
31 {
32 object temp = defaultValue;
33
34 try
35 {
36 temp = this.GetValue(key, type);
37 }
38 catch (InvalidOperationException) { }
39
40 return temp;
41 }
42
43
44 /// <summary>Sets the value for a specified key in the .config file.</summary>
45 /// <param name="key">The key for which to set the value.</param>
46 /// <param name="value">The value to save to the AppConfig.</param>
47 /// <returns>Whether or not the set operation was successful.</returns>
48 public bool SetValue(string key, string value)
49 {
50 XmlDocument cfgDoc = new XmlDocument();
51 loadConfigDoc(cfgDoc);
52
53 // Get the appSettings node.
54 XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
55 if (node == null)
56 {
57 throw new System.InvalidOperationException("appSettings section not found");
58 }
59
60 try
61 {
62 // Get the element we want to update.
63 XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
64
65 if (addElem != null)
66 {
67 // Update the element.
68 addElem.SetAttribute("value", value);
69 }
70 else
71 {
72 // The element wasn't there -- create it.
73 XmlElement entry = cfgDoc.CreateElement("add");
74 entry.SetAttribute("key", key);
75 entry.SetAttribute("value", value);
76 node.AppendChild(entry);
77 }
78
79 // Save it.
80 saveConfigDoc(cfgDoc, docName);
81 }
82 catch
83 {
84 return false;
85 }
86
87 return true;
88 }
89
90
91 /// <summary>Remove the specified key from the .config file.</summary>
92 /// <param name="key">The key to remove.</param>
93 /// <returns>Whether or not the remove operation was successful.</returns>
94 public bool RemoveElement(string key)
95 {
96 try
97 {
98 XmlDocument cfgDoc = new XmlDocument();
99 loadConfigDoc(cfgDoc);
100
101 // Get the appSettings node.
102 XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
103 if (node == null)
104 {
105 throw new System.InvalidOperationException("appSettings section not found");
106 }
107
108 // Remove the element.
109 node.RemoveChild(node.SelectSingleNode("//add[@key='" + key + "']"));
110
111 // Save it.
112 saveConfigDoc(cfgDoc, docName);
113 }
114 catch
115 {
116 return false;
117 }
118
119 return true;
120 }
121
122
123 // Load the config file.
124 private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
125 {
126 cfgDoc.Load(docName);
127 return cfgDoc;
128 }
129
130
131 // Save the config file.
132 private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
133 {
134 XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
135 writer.Formatting = Formatting.Indented;
136 cfgDoc.WriteTo(writer);
137 writer.Flush();
138 writer.Close();
139 }
140 }

 

 public class AppConfig : AppSettingsReader
    {
        private string docName = string.Empty;


        // Singleton fun.
        private static AppConfig instance;
        static AppConfig() { instance = new AppConfig(); }
        private AppConfig()
            : base()
        {
            docName = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Assembly.GetEntryAssembly().GetName().Name + ".exe.config");
        }


        /// <summary>Gets the current AppConfig instance.</summary>
        static public AppConfig Instance
        {
            get { return instance; }
        }


        /// <summary>Gets the value for a specified key from the AppSettings property and returns an object
        /// of the specified type containing the value from the .config file.</summary>
        /// <param name="key">The key for which to get the value.</param>
        /// <param name="type">The type of the object to return.</param>
        /// <param name="defaultValue">The value to return if the specified key cannot be found.</param>
        /// <returns>The value of the specified key.</returns>
        /// <remarks>If the key is not found, then the value provided in defaultValue is returned.</remarks>
        public object GetValue(string key, Type type, object defaultValue)
        {
            object temp = defaultValue;

            try
            {
                temp = this.GetValue(key, type);
            }
            catch (InvalidOperationException) { }

            return temp;
        }


        /// <summary>Sets the value for a specified key in the .config file.</summary>
        /// <param name="key">The key for which to set the value.</param>
        /// <param name="value">The value to save to the AppConfig.</param>
        /// <returns>Whether or not the set operation was successful.</returns>
        public bool SetValue(string key, string value)
        {
            XmlDocument cfgDoc = new XmlDocument();
            loadConfigDoc(cfgDoc);

            // Get the appSettings node.
            XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
            if (node == null)
            {
                throw new System.InvalidOperationException("appSettings section not found");
            }

            try
            {
                // Get the element we want to update.
                XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

                if (addElem != null)
                {
                    // Update the element.
                    addElem.SetAttribute("value", value);
                }
                else
                {
                    // The element wasn't there -- create it.
                    XmlElement entry = cfgDoc.CreateElement("add");
                    entry.SetAttribute("key", key);
                    entry.SetAttribute("value", value);
                    node.AppendChild(entry);
                }

                // Save it.
                saveConfigDoc(cfgDoc, docName);
            }
            catch
            {
                return false;
            }

            return true;
        }


        /// <summary>Remove the specified key from the .config file.</summary>
        /// <param name="key">The key to remove.</param>
        /// <returns>Whether or not the remove operation was successful.</returns>
        public bool RemoveElement(string key)
        {
            try
            {
                XmlDocument cfgDoc = new XmlDocument();
                loadConfigDoc(cfgDoc);

                // Get the appSettings node.
                XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
                if (node == null)
                {
                    throw new System.InvalidOperationException("appSettings section not found");
                }

                // Remove the element.
                node.RemoveChild(node.SelectSingleNode("//add[@key='" + key + "']"));

                // Save it.
                saveConfigDoc(cfgDoc, docName);
            }
            catch
            {
                return false;
            }

            return true;
        }


        // Load the config file.
        private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
        {
            cfgDoc.Load(docName);
            return cfgDoc;
        }


        // Save the config file.
        private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
        {
            XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
            writer.Formatting = Formatting.Indented;
            cfgDoc.WriteTo(writer);
            writer.Flush();
            writer.Close();
      
public class AppConfig : AppSettingsReader
{
private string docName = string.Empty;


// Singleton fun.
private static AppConfig instance;
static AppConfig() { instance = new AppConfig(); }
private AppConfig()
:
base()
{
docName
= Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Assembly.GetEntryAssembly().GetName().Name + ".exe.config");
}


/// <summary>Gets the current AppConfig instance.</summary>
static public AppConfig Instance
{
get { return instance; }
}


/// <summary>Gets the value for a specified key from the AppSettings property and returns an object
/// of the specified type containing the value from the .config file.</summary>
/// <param name="key">The key for which to get the value.</param>
/// <param name="type">The type of the object to return.</param>
/// <param name="defaultValue">The value to return if the specified key cannot be found.</param>
/// <returns>The value of the specified key.</returns>
/// <remarks>If the key is not found, then the value provided in defaultValue is returned.</remarks>
public object GetValue(string key, Type type, object defaultValue)
{
object temp = defaultValue;

try
{
temp
= this.GetValue(key, type);
}
catch (InvalidOperationException) { }

return temp;
}


/// <summary>Sets the value for a specified key in the .config file.</summary>
/// <param name="key">The key for which to set the value.</param>
/// <param name="value">The value to save to the AppConfig.</param>
/// <returns>Whether or not the set operation was successful.</returns>
public bool SetValue(string key, string value)
{
XmlDocument cfgDoc
= new XmlDocument();
loadConfigDoc(cfgDoc);

// Get the appSettings node.
XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}

try
{
// Get the element we want to update.
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

if (addElem != null)
{
// Update the element.
addElem.SetAttribute("value", value);
}
else
{
// The element wasn't there -- create it.
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute(
"key", key);
entry.SetAttribute(
"value", value);
node.AppendChild(entry);
}

// Save it.
saveConfigDoc(cfgDoc, docName);
}
catch
{
return false;
}

return true;
}


/// <summary>Remove the specified key from the .config file.</summary>
/// <param name="key">The key to remove.</param>
/// <returns>Whether or not the remove operation was successful.</returns>
public bool RemoveElement(string key)
{
try
{
XmlDocument cfgDoc
= new XmlDocument();
loadConfigDoc(cfgDoc);

// Get the appSettings node.
XmlNode node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}

// Remove the element.
node.RemoveChild(node.SelectSingleNode("//add[@key='" + key + "']"));

// Save it.
saveConfigDoc(cfgDoc, docName);
}
catch
{
return false;
}

return true;
}


// Load the config file.
private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
{
cfgDoc.Load(docName);
return cfgDoc;
}


// Save the config file.
private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
{
XmlTextWriter writer
= new XmlTextWriter(cfgDocPath, null);
writer.Formatting
= Formatting.Indented;
cfgDoc.WriteTo(writer);
writer.Flush();
writer.Close();
}
}

 

  }
    }
posted @ 2009-12-04 10:29  chunchill  阅读(329)  评论(0编辑  收藏  举报