By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,225 Members | 2,170 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,225 IT Pros & Developers. It's quick & easy.

read machine.config

P: n/a
It works with VS2003 and does not in VS2005:

in VS2003 :
string sMyvalue = ConfigurationSettings.AppSettings["MyKey"];

in VS2005 (does not work!!)
string sMyvalue = ConfigurationManager.AppSettings["MyKey"];

Anybody able to give me idea how-to read by C# element which I add to the
machine.config into the new single section?

<MyNode>
<add name ="MyKey" value="MyValue"/>
</MyNode>
Thank you,
Vitaliy Krasner
Nov 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
i don t like using built in method Configuration.AppSettings since it only
provides read method not write so i use something i found and made. this
reads and writes bo config files.

I don t have 2005 so i can t help you with your specific problem but i am
including my class i use for application settings read/write.

hope this helps and pass it along to others if you wish :)

using System;

using System.Xml;

using System.Reflection;

using System.Configuration;

using System.Windows.Forms;

using System.Collections;

namespace SOMENAMESPACE

{

#region AppSettings Class

/// <summary>

/// Summary description for AppSettings.

/// </summary>

///<app.config>

///

///<?xml version="1.0" encoding="utf-8" ?>

///<configuration>

///<appSettings>

///<add key="ircroom" value="#jami"/>

///<add key="server" value="lucky"/>

///<add key="port" value="6667"/>

///</appSettings>

///</configuration>

///</app.config>

///<example>

///

///AppSettings app = new
AppSettings(((Assembly.GetEntryAssembly()).GetName ()).Name+".exe.config");

///mIRCRoom = app.GetValue("//appSettings//add[@key='ircroom']"); //reads

///mServer = app.GetValue("//appSettings//add[@key='server']"); //reads

///app.SetValue("//appSettings//add[@key='port']"

///

///</example>

///

public class AppSettings : System.Configuration.AppSettingsReader

{

#region Variable Declarations

#region Private Variables

/// <summary> xmlnode</summary>

private XmlNode mXmlNode;

/// <summary> config file name</summary>

private string mConfigFile;

#endregion

#endregion

#region Constructor

/// <summary>

/// appsetting reads and writes to any given xml file

/// pass the xml file name in

/// </summary>

/// <param name="file">xml file name to read from and write to</param>

/// <example> to read or write to the following key

/// "<appSettings><add key="ircroom" value="#jami"/></appSettings>

/// use //appSettings//add[@key='ircroom']

///

///</example>

public AppSettings(string file)

{

ConfigFileName = Application.StartupPath+"\\"+file;
}

#endregion

#region Public Methods

/// <summary>

/// gets key as an xml object, converts to string and reutrns the string

/// </summary>

/// <param name="key"></param>

/// <returns>string key</returns>

public string GetValue(string key)

{

return Convert.ToString(GetValue(key,typeof(string)));

}

/// <summary>

/// takes key and type of the string, ie.string, bool, int, double,DateTime

/// </summary>

/// <param name="key"></param>

/// <param name="sType"></param>

/// <returns>convert value to given type parameter and returns an
object</returns>

public new object GetValue(string key, System.Type sType)

{

XmlDocument doc = new XmlDocument();

object ro = String.Empty;

LoadConfigFile(doc);

string sNode = key.Substring(0, key.LastIndexOf("//"));

try

{

mXmlNode = doc.SelectSingleNode(sNode);

if(mXmlNode != null)

{

XmlElement targetElement =
(XmlElement)mXmlNode.SelectSingleNode(key.Replace( sNode,""));

if(targetElement != null)

{

ro = targetElement.GetAttribute("value");

}

}

if(sType == typeof(string))

{

return Convert.ToString(ro);

}

else if(sType == typeof(bool))

{

if(ro.Equals("True") || ro.Equals("False"))

return Convert.ToBoolean(ro);

else

return false;

}

else if(sType == typeof(int))

{

return Convert.ToInt32(ro);

}

else if(sType == typeof(double))

{

return Convert.ToDouble(ro);

}

else if(sType == typeof(DateTime))

{

return Convert.ToDateTime(ro);

}

else

return Convert.ToString(ro);

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

return String.Empty;

}

}

/// <summary>

/// sets value of given key val pair

/// if it does not exisist it will create one

/// </summary>

/// <param name="key"></param>

/// <param name="val"></param>

/// <returns>boolean indicating success or failure</returns>

/// <example>settings.SetValue("//RoomSettings//add[@key='port']",
</example>

public bool SetValue(string key, string val)

{

XmlDocument doc = new XmlDocument();

LoadConfigFile(doc);

try

{

//configuration

string sNode = key.Substring(0, key.LastIndexOf("//"));

mXmlNode = doc.SelectSingleNode(sNode);

if(mXmlNode == null) return false;

XmlElement targetElement = (XmlElement)
mXmlNode.SelectSingleNode(key.Replace(sNode, null));

if(targetElement != null)

{//element found so set it

targetElement.SetAttribute("value", val);

}

else //create a new element

{

//add[@key='room']

sNode = key.Substring(key.LastIndexOf("//")+ 2);

//create new element add

XmlElement entry =
doc.CreateElement(sNode.Substring(0,sNode.IndexOf( "[@")).Trim());

sNode = sNode.Substring(sNode.IndexOf("'")+1);

//set attribute key=yyy

entry.SetAttribute("key",sNode.Substring(0,sNode.I ndexOf("'")));

//set attribute value=val

entry.SetAttribute("value",val);

mXmlNode.AppendChild(entry);

}

SaveConfigFile(doc,mConfigFile);

return true;

}

catch{ return false; }

}
/// <summary>

/// removes give key and its value

/// </summary>

/// <param name="key"></param>

/// <returns>returns boolean value indicating success or failure</returns>

public bool removeElement (string key)

{

XmlDocument doc = new XmlDocument();

LoadConfigFile(doc);

try

{

string sNode = key.Substring(0, key.LastIndexOf("//"));

// retrieve the appSettings node

mXmlNode = doc.SelectSingleNode("//appSettings");

if( mXmlNode == null )

return false;

// XPath select setting element that contains the key to remove

mXmlNode.RemoveChild( mXmlNode.SelectSingleNode(key.Replace(sNode,"")) );

SaveConfigFile (doc, mConfigFile);

return true;

}

catch

{

return false;

}

}

#endregion

#region Private Methods

/// <summary>

/// Loads xml document that is myprog.exe.config

/// </summary>

/// <param name="doc"></param>

private void LoadConfigFile(XmlDocument doc)

{

try

{

doc.Load(mConfigFile);

}

catch(XmlException ex)

{

System.Diagnostics.Debug.WriteLine(ex.Message);

}

catch(Exception ex)

{

System.Diagnostics.Debug.WriteLine(ex.Message);

}

}

/// <summary>

/// saves config gile

/// </summary>

/// <param name="doc">document to save</param>

/// <param name="docPath">document path where to save</param>

private void SaveConfigFile(XmlDocument doc, string docPath)

{

try

{

XmlTextWriter writer = new XmlTextWriter(docPath, null);

writer.Formatting = Formatting.Indented;

doc.WriteTo( writer );

writer.Flush();

writer.Close();

return;

}

catch

{

}

}

#endregion

#region Public Properties

/// <summary>

/// returns or set config file name

/// </summary>

public string ConfigFileName

{

get

{

return mConfigFile;

}

set

{

mConfigFile = value;

}

}

#endregion

}

#endregion

}
Nov 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.