473,387 Members | 1,534 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

read machine.config

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
1 5283
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Marina Anufreichik | last post by:
Hi, After deploymnet web application on web server I can access page on local machine and login fine but when I'm trying to access web site from remote machine I can see login page, but when I'm...
7
by: | last post by:
In the beginning we had Ini files. Later we had registery files. Now have xml files and our read-only myapp.config file. My question now, is what is the best way to store and load user and...
1
by: Brian Patterson | last post by:
Hi - I'm trying to manually read and parse Machine.Config. When I try this I recieve the following error: Access to the path "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\" is denied. I am...
4
by: Chris V | last post by:
I'm having a problem deploying my ASP.NET application to a WIN2k server. (IIS5 .NET 1.1) When I try to access ConfigurationSettings.AppSettings("WhateverValue") I get an "Object reference not...
7
by: Bob | last post by:
It's great that VS.NET makes it so effortless to add a web reference to a web service. The problem is, I haven't figured out a way to configure the URLs (or simply switch the references to another...
4
by: Josema | last post by:
Hi to all, Im searching a hand to solve an Exception that i get when i try to give the user to a gmail account... Any help would be appreciated.. Thanks in advance This is a piece of my...
2
by: Max Metral | last post by:
I'm trying to set the default behavior of customErrors in the machine.config. The documentation seems to suggest this should work, but it doesn't seem to work for me. On my development machine, I...
4
by: klynn | last post by:
Hi: I'm having problems reading a Microsoft Access file from my ASP.Net app on a Windows Server 2003 machine. The error message: The Microsoft database engine cannot open the file, <my_file>. It...
2
by: =?Utf-8?B?U2JhdGNodQ==?= | last post by:
How will i read connection strings in all web.config files in one particualr machine?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.