使用连接字符串详细信息读取XML文件

时间:2011-03-02 00:04:03

标签: c# sql xml string connection

我在My Project中使用一个表单创建了一个XML文件,该表单包含运行程序所需的连接字符串详细信息。 XML的格式如下:

<xml encoding="UTF8">
<configuration>
   <appsettings>
     <servername>localhost</servername>
     <serverport>1433</serverport>
     <username>sa</username>
     <password>thepassword</password>
     <database>NorthWind</database>
   </appsettings>
</configuration>
</xml>

我需要使用节点中的参数来构建我的连接字符串以运行查询并转储Excel文件。有人可以告诉我如何将其写入我的主表单中的连接字符串。

2 个答案:

答案 0 :(得分:2)

就个人而言,我建议使用内置(和首选方式)在.NET中执行此操作。这有两个方面: 1.使用application.config文件(或ASP.NET的web.config) 2.在这些配置文件上使用ConnectionStrings部分。

配置文件是存储应用程序配置信息的首选方式,.NET有很多内置支持。此外,还有对连接字符串的内置支持。

因此,例如,您的application.config文件(在Visual Studio中,右键单击解决方案资源管理器中的项目节点并选择“添加|新项...”,当该对话框打开时,选择“应用程序配置文件”)< / p>

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Orion" providerName="System.Data.SqlClient" connectionString="server=.\SQLEXPRESS;database=Orion;Integrated Security=True"/>
  </connectionStrings>
</configuration>

注意connectionStrings部分。有一个条目(ConnectionStrings节点的子节点)。您可以在其中提供所需的任何名称,该节点的connectionString属性将包含您需要的连接字符串。我假设你知道连接字符串需要什么。

现在在你的应用程序中,你会做这样的事情:

  internal partial class DataModule
  {
    private DbProviderFactory DbProviderFactory { get; set; }
    private DbConnection DbConnection { get; set; }

    public DataModule()
    {
      var connectionStringSettings = ConfigurationManager.ConnectionStrings["Orion"];
      DbProviderFactory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
      DbConnection = DbProviderFactory.CreateConnection();
      DbConnection.ConnectionString = connectionStringSettings.ConnectionString;
    }
  }

请注意,在此代码中,我引用了“Orion”连接的“名称”。请务必将其更改为您为连接提供的任何名称。

此设计还允许您在配置文件和应用程序中定义多个“连接”,您可以选择使用其中任何一个(或多个)。例如:

  <connectionStrings>
    <add name="Orion" providerName="System.Data.SqlClient" connectionString="server=.\SQLEXPRESS;database=Orion;Integrated Security=True"/>
    <add name="MyOtherOrion" providerName="System.Data.SqlClient" connectionString="server=myserver\myinstancename;database=Orion;uid=myusername;password=mypassword"/>
  </connectionStrings>

然后在您的应用程序中,您可以切换到使用“MyOtherOrion”连接。

答案 1 :(得分:1)

正确的方法是使用App.Config,如:http://msdn.microsoft.com/en-us/library/ms254494(v=VS.100).aspx

如果这不是一个选项,你可以使用一些Linq To Xml如果你想要(空检查等,排除): 哦,用适当的连接字符串格式替换“MyConnectionStringFormatString”:)。

XDocument doc = XDocument.Parse(xml);

String conStr = 
    doc.Root
    .Elements("configuration")
    .Elements("appsettings")
    .Select(
        s => 
            String.Format("MyConnectionStringFormatString {0}-{1}-{2}-{3}-{4}",
            s.Elements("servername").Single().Value,
            s.Elements("serverport").Single().Value,
            s.Elements("username").Single().Value,
            s.Elements("password").Single().Value,
            s.Elements("database").Single().Value));