配置文件App.config、Web.config 读写操作

 

一、读取配置文件

       1.在项目工程里添加System.Configuration程序集引用

       

      

    2. App.config配置文件位置在于 该程序的根目录bin文件夹 的子文件夹Debug文件夹里边

       注意:App.config和WindowsFormsApplication1.exe.config是同一个东西

    

   3.在程序中打开App.config配置文件

      

    标准的App.config配置文件内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

4.进行配置读取,以读取数据库连接字符串为代码示例

   首先需要在<configuration></configuration>节点里边添加配置节点 <connectionStrings></connectionStrings>  或者 <appSettings></appSettings>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
   <!--第一种配置方式-->
  <connectionStrings>
    <add name="conStr1" connectionString="Data Source=你的服务器名;Initial Catalog=你的数据库名;User ID=你的账号;Password=你的密码" providerName="System.Data.SqlClient" />
  </connectionStrings>

  <!--第二种配置方式-->
  <appSettings>
    <add key="ConStr2" value="Data Source=服务器名;Initial Catalog=数据库名;User ID=账号;Password=密码;"/>
  </appSettings>

</configuration>

  在程序中读取配置,我们使用第二种配置方式

string constr=ConfigurationManager.AppSettings["conStr2"]

  第一种配置方式读取,可专用于数据库连接字符串更友好。第二种方式比较通用

  第一种配置方式示例:

string str=ConfigurationManager.ConnectionStrings["conStr1"].ConnectionString;

注意:第一种配置方式特性说明:

providerName="System.Data.SqlClient" ----说明使用的是MSSQLServer数据库

providerName="System.Data.SqlLite" ----说明使用的是SQLLite数据库

providerName="System.Data.OracleClient"  或 providerName="System.Data.Oracle.DataAccess.Client" ----说明使用的是Oracle数据库

providerName="System.Data.OleDb" ----说明使用的是Access数据库

封装成方法调用方式  GetConfig("传入具体的key值")

 public static string GetConfig(string strKey)
        {
            AppSettingsReader appReader = new AppSettingsReader();
            string strReturn;
            try
            {
                strReturn = appReader.GetValue(strKey, typeof(string)).ToString();
            }
            catch (Exception ex)
            {
                strReturn = ex.Message.ToString();
            }
            finally
            {
                appReader = null;

            }
            return strReturn;
        }

 如果不想配置节点过多,只需要配置一个key 和value 方式 ,这里使用  | 隔开。也可以使用其他符号隔开。

<add key="str" value="1|2|3"/>

示例:    调用方式   GetAllConfigList(str)   返回一个List集合

public List<string> GetAllConfigList(string indexOf)
        {
            List<string> vaList=new List<string>();
            AppSettingsReader reader = new AppSettingsReader();
            NameValueCollection appStgs = ConfigurationManager.AppSettings;
            string[] names = ConfigurationManager.AppSettings.AllKeys;
            string value = string.Empty;
            for (int i = 0; i < appStgs.Count; i++)
            {

                string key = names[i];
                if (key.IndexOf(indexOf) >= 0)
                {
                    value = (string)reader.GetValue(key, value.GetType());
                   
                    string[] strValue = value.Split('|');
                    for (int j = 0; j < strValue.Length; j++)
                    {
                        vaList.Add(strValue[j]);
                    }
                }
            }

            return vaList;
        }

   注意事项:

1.配置方式一 是一种用于读数据库连接字符串的方式, 结尾的 providerName 需要根据程序使用的数据库,引用对应的程序集,也就是dll.

2. 以上示例使用 Sql server 数据库连接字符串。如果是使用其他数据库,只需要更改连接字符串即可.

数据库连接字符串:

Orale

User Id=你的账户名;Password=密码;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=主机地址)(PORT=端口号)))(CONNECT_DATA=(SERVICE_NAME=ORCL)))

Sql server   远程连接方式使用示例1,本地使用不需要账户密码使用示例2

示例1

Data Source=你的服务器名;Initial Catalog=你的数据库名;User ID=数据库账号;Password=密码

示例2  如果是本地服务器: 可用 . 

Data Source=服务器名;Initial Catalog=你连接的数据库;Integrated Security=True

My Sql   本地是localhost  ,远程写入具体ip

Data Source=localhost;Database=使用的数据库;User ID=账户;Password=密码"

小技巧:

1.以上方式也适用于Web.config 配置文件。

2.如果项目工程没有App.config配置文件,但是代码一些变量值不想写死怎么办,想搞个配置文件怎么弄?这就需要手动添加配置文件了。

 比如项目工程命名为 "你好.exe"  可执行程序。在该 "你好.exe" 可执行程序下面添加一个txt文件,重命名为 '你好.exe.config"。然后把标准的App.config配置文件的节点复制粘贴进去

按照上面步骤添加配置。然后在程序中使用即可。

3.重要事件说三次:App.config xx.exe.config 文件是同一种东西

二、写配置文件

 1.代码示例

 public void WriteConfig(string key, string value)
        {
            XmlDocument doc01 = new XmlDocument();
            XmlDocument doc02 = new XmlDocument();
            //获得配置文件的全路径  
            string strFileName01 = System.IO.Path.Combine((Application.StartupPath + @"\"), "你好.exe.config");
            string path = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo dir = Directory.GetParent(path);
            string strFileName02 = dir.Parent.Parent.FullName + "\\app.config";
            doc01.Load(strFileName01);
            doc02.Load(strFileName02);
            //找出名称为“add”的所有元素  
            XmlNodeList nodes01 = doc01.GetElementsByTagName("add");
            XmlNodeList nodes02 = doc02.GetElementsByTagName("add");
            for (int i = 0; i < nodes01.Count; i++)
            {
                //获得将当前元素的key属性  
                XmlAttribute att = nodes01[i].Attributes["key"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att.Value == key)
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes01[i].Attributes["value"];
                    att.Value = value;
                    break;
                }
            }
            for (int i = 0; i < nodes02.Count; i++)
            {
                //获得将当前元素的key属性  
                XmlAttribute att = nodes02[i].Attributes["key"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att.Value == "ftpServer")
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes02[i].Attributes["value"];
                    att.Value = value;
                    break;
                }
            }
            //保存上面的修改  
            doc01.Save(strFileName01);
            doc01.Save(strFileName02);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");

        }

2.调用方式 WriteConfig("读写入的那项key","写入的值")

说明:以上参考各大网友代码,如有侵权,删。

猜你喜欢

转载自blog.csdn.net/weixin_39237340/article/details/92561824