简体   繁体   中英

Read/write Database Connection string in xml file using c# Windows Form

I am developing an c# application in which I need to fetch data from oracle database server. In my application I do not want to make a hard coded connection string because sometimes we have to connect it with different DB (for testing purpose it has same schema).

For this I have a plan that I create an xml file and a new form(with admin rights) using this form I update/insert database credentials in xml file or use app.config , but the problem is i don't have any idea how to read and write xml file in predefined manner (in same manner as a connection string should be).

Can you please help me out for creating new xml file or have any batter idea?

how about this code?

public static string ClientName, DbType, ConnectionString;
        static DB()
        {
            try
            {
                DataTable Dt = new DataTable("Settings");
                DataColumn Client = new DataColumn("Client", typeof(string));
                DataColumn DataBaseType = new DataColumn("DataBaseType", typeof(string));

                DataColumn ConString = new DataColumn("ConnectionString", typeof(string));
                Dt.Columns.Add(Client);
                Dt.Columns.Add(DataBaseType);
                Dt.Columns.Add(ConString);
                Dt.ReadXml(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Settings.xml");
                DB.ClientName = Dt.Rows[0]["Client"].ToString();
                DB.DbType = Dt.Rows[0]["DataBaseType"].ToString();
                DB.Port = Dt.Rows[0]["Port"].ToString();
                DB.ConnectionString = Dt.Rows[0]["ConnectionString"].ToString();
            }
            catch(Exception ex)
             {
            // Exception message
             }

and xml file code is

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
    <Settings>
        <Client>DSCL</Client>
        <DataBaseType>ORACLE</DataBaseType>

            <ConnectionString>providerName=system.data.oracleclient;User ID=****;password=****;Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;</ConnectionString>

  </Settings>
</DocumentElement>

Create that class

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap ...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Also take a look at

Loading custom configuration files

http://www.codeproject.com/Articles/32490/Custom-Configuration-Sections-for-Lazy-Coders

App.Config:

<configuration>     
  <connectionStrings>
    <add name="connstring1"
        connectionString="DataSource=123.123.123.123;UserID=XXX;Password=XXX;" />
  </connectionStrings>     
</configuration>

C# code:

var appConfig = ConfigurationManager.OpenExeConfiguration("your.exe");
string connectionstring = appConfig.ConnectionStrings.ConnectionStrings["connstring1"].ConnectionString;

use the app config for your connectionStrings:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
 <connectionStrings>
    <add name="MyDatabase" connectionString="......"/>
 </connectionStrings>
</configuration>

add a reference to System.Configuration in your application and get the connection string via :

string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;

You are trying to reinvent a wheel.

As people mentioned here, .config files are meant for application configuration. There is a dedicated section for connection strings in them, so you're advised to use it as it is standard and convenient.

Here is your config:

<configuration>
....
<connectionStrings>
    <add name="OracleConnectionString" connectionString="providerName=system.data.oracleclient;User ID=****;password=****;Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;" providerName="System.Data.OracleClient" />
</connectionStrings>
</configuration>

and here is the code snippet to modify it:

string user = "Me";
string pwd = "qwerty";

Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection section = (ConnectionStringsSection)cfg.GetSection("connectionStrings");

var currentConnectionString = section.ConnectionStrings["OracleConnectionString"];
currentConnectionString.ConnectionString = string.Format("providerName=system.data.oracleclient;User ID={0};password={1};Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;", user, pwd);

cfg.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Notes: 1. Be aware that you are saving .config in the /bin, not in your project folder, so when you rerun/redeploy your application, the changes will be discarded. 2. When debugging you won't see the changes as VS creates HOST process and copies a fresh .config file to the /bin. To see the changes you should run without debugging. Cheers.

Create a datatable with your values. do Dt.WriteXml(fileName); It will generate xml file. maintain this xml in future. use Dt.ReadXml(filename) to get the values back in application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM