[quoted text, click to view] "Adriano" <adriano@tadaz.com> wrote in message news:eQIlkIioEHA.3876@TK2MSFTNGP15.phx.gbl...
> Can anyone send me the code for reading and modifying that values please,
Yes, here's what the code you requested would look like using an
XmlSerializer.
- - - CustomConfig.cs
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
internal class DbSettings
{
private string dbhost;
private string dbuser;
private string dbpass;
private string dbname;
public DbSettings()
{
this.dbhost = "";
this.dbuser = "";
this.dbpass = "";
this.dbname = "";
}
[XmlElement( "dbhost")]
public string Host
{
get { return this.dbhost; }
set { this.dbhost = value; }
}
[XmlElement( "dbuser")]
public string User
{
get { return this.dbuser; }
set { this.dbuser = value; }
}
[XmlElement( "dbpass")]
public string Password
{
get { return this.dbpass; }
set { this.dbpass = value; }
}
[XmlElement( "dbname")]
public string Name
{
get { return this.dbname; }
set { this.dbname = value; }
}
}
[XmlRoot( "configuration")]
public class CustomConfig
{
private DbSettings dbSettings;
public CustomConfig( )
{
this.dbSettings = new DbSettings( );
}
[XmlElement( "dbSettings")]
public DbSettings DbSettings
{
get { return this.dbSettings; }
set { this.dbSettings = value; }
}
public static CustomConfig Load( )
{
XmlSerializer serializer = new XmlSerializer( typeof( CustomConfig));
XmlSerializerNamespaces serialNs = new XmlSerializerNamespaces();
serialNs.Add( "", "");
XmlTextReader reader = new XmlTextReader( "config.xml");
CustomConfig cfig = serializer.Deserialize( reader) as CustomConfig;
reader.Close();
return cfig;
}
public static void Save( CustomConfig cfig)
{
StreamWriter writer = new StreamWriter( "config.xml", false, Encoding.UTF8);
serializer.Serialize( writer, cfig, serialNs);
writer.Flush( );
writer.Close( );
}
}
public class TestCustomConfig
{
public static void Main( )
{
CustomConfig config = CustomConfig.Load( );
if ( config != null )
{
Console.WriteLine( config.DbSettings.Host);
Console.WriteLine( config.DbSettings.User);
Console.WriteLine( config.DbSettings.Password);
Console.WriteLine( config.DbSettings.Name);
}
// Change Database Name.
config.DbSettings.Name = "pubs";
CustomConfig.Save( config);
}
}
- - -
Note that this places the password in plain-text.
For purposes of a config file, I'd really encourage you to look into
the System.Configuration namespace, which handles a lot of this
automatically as long as your config file is named
applicationname.exe.config
or,
web.config
Derek Harmon