欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解在.net中讀寫config文件的各種方法

 更新時間:2016年12月20日 10:05:59   作者:Fish Li  
本篇文章主要介紹了在.net中讀寫config文件的各種方法,詳細(xì)的介紹各種配置文件的讀寫操作,具有一定的參考價值,有興趣的可以了解一下。

今天談?wù)勗?net中讀寫config文件的各種方法。 在這篇博客中,我將介紹各種配置文件的讀寫操作。 由于內(nèi)容較為直觀,因此沒有過多的空道理,只有實實在在的演示代碼, 目的只為了再現(xiàn)實戰(zhàn)開發(fā)中的各種場景。希望大家能喜歡。

通常,我們在.NET開發(fā)過程中,會接觸二種類型的配置文件:config文件,xml文件。 今天的博客示例也將介紹這二大類的配置文件的各類操作。 在config文件中,我將主要演示如何創(chuàng)建自己的自定義的配置節(jié)點,而不是介紹如何使用appSetting 。

請明:本文所說的config文件特指app.config或者web.config,而不是一般的XML文件。 在這類配置文件中,由于.net framework已經(jīng)為它們定義了一些配置節(jié)點,因此我們并不能簡單地通過序列化的方式去讀寫它。

config文件 - 自定義配置節(jié)點

為什么要自定義的配置節(jié)點?

確實,有很多人在使用config文件都是直接使用appSetting的,把所有的配置參數(shù)全都塞到那里,這樣做雖然不錯, 但是如果參數(shù)過多,這種做法的缺點也會明顯地暴露出來:appSetting中的配置參數(shù)項只能按key名來訪問,不能支持復(fù)雜的層次節(jié)點也不支持強類型, 而且由于全都只使用這一個集合,你會發(fā)現(xiàn):完全不相干的參數(shù)也要放在一起!

想擺脫這種困擾嗎?自定義的配置節(jié)點將是解決這個問題的一種可行方法。

首先,我們來看一下如何在app.config或者web.config中增加一個自定義的配置節(jié)點。 在這篇博客中,我將介紹4種自定義配置節(jié)點的方式,最終的配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" />
    <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" />
    <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" />
    <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" />
  </configSections>

  <MySection111 username="fish-li" url="http://www.dbjr.com.cn/"></MySection111>

  <MySection222>
    <users username="fish" password="liqifeng"></users>
  </MySection222>

  <MySection444>
    <add key="aa" value="11111"></add>
    <add key="bb" value="22222"></add>
    <add key="cc" value="33333"></add>
  </MySection444>

  <MySection333>
    <Command1>
      <![CDATA[
        create procedure ChangeProductQuantity(
          @ProductID int,
          @Quantity int
        )
        as
        update Products set Quantity = @Quantity 
        where ProductID = @ProductID;
      ]]>
    </Command1>
    <Command2>
      <![CDATA[
        create procedure DeleteCategory(
          @CategoryID int
        )
        as
        delete from Categories
        where CategoryID = @CategoryID;
      ]]>
    </Command2>
  </MySection333>  
</configuration>

同時,我還提供所有的示例代碼(文章結(jié)尾處可供下載),演示程序的界面如下:

config文件 - Property

先來看最簡單的自定義節(jié)點,每個配置值以屬性方式存在:

<MySection111 username="fish-li" url="http://www.dbjr.com.cn/"></MySection111>

實現(xiàn)代碼如下:

public class MySection1 : ConfigurationSection
{
  [ConfigurationProperty("username", IsRequired = true)]
  public string UserName
  {
    get { return this["username"].ToString(); }
    set { this["username"] = value; }
  }

  [ConfigurationProperty("url", IsRequired = true)]
  public string Url
  {
    get { return this["url"].ToString(); }
    set { this["url"] = value; }
  }
}

小結(jié):

1. 自定義一個類,以ConfigurationSection為基類,各個屬性要加上[ConfigurationProperty] ,ConfigurationProperty的構(gòu)造函數(shù)中傳入的name字符串將會用于config文件中,表示各參數(shù)的屬性名稱。

2. 屬性的值的讀寫要調(diào)用this[],由基類去保存,請不要自行設(shè)計Field來保存。

3. 為了能使用配置節(jié)點能被解析,需要在<configSections>中注冊: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要與<MySection111 ..... >是對應(yīng)的。

說明:下面將要介紹另三種配置節(jié)點,雖然復(fù)雜一點,但是一些基礎(chǔ)的東西與這個節(jié)點是一樣的,所以后面我就不再重復(fù)說明了。

config文件 - Element

再來看個復(fù)雜點的,每個配置項以XML元素的方式存在:

<MySection222>
  <users username="fish" password="liqifeng"></users>
</MySection222>

實現(xiàn)代碼如下:

public class MySection2 : ConfigurationSection
{
  [ConfigurationProperty("users", IsRequired = true)]
  public MySectionElement Users
  {
    get { return (MySectionElement)this["users"]; }
  }
}

public class MySectionElement : ConfigurationElement
{
  [ConfigurationProperty("username", IsRequired = true)]
  public string UserName
  {
    get { return this["username"].ToString(); }
    set { this["username"] = value; }
  }

  [ConfigurationProperty("password", IsRequired = true)]
  public string Password
  {
    get { return this["password"].ToString(); }
    set { this["password"] = value; }
  }
}

小結(jié):

1. 自定義一個類,以ConfigurationSection為基類,各個屬性除了要加上[ConfigurationProperty] 

2. 類型也是自定義的,具體的配置屬性寫在ConfigurationElement的繼承類中。

config文件 - CDATA

有時配置參數(shù)包含較長的文本,比如:一段SQL腳本,或者一段HTML代碼,那么,就需要CDATA節(jié)點了。假設(shè)要實現(xiàn)一個配置,包含二段SQL腳本:

<MySection333>
  <Command1>
    <![CDATA[
      create procedure ChangeProductQuantity(
        @ProductID int,
        @Quantity int
      )
      as
      update Products set Quantity = @Quantity 
      where ProductID = @ProductID;
    ]]>
  </Command1>
  <Command2>
    <![CDATA[
      create procedure DeleteCategory(
        @CategoryID int
      )
      as
      delete from Categories
      where CategoryID = @CategoryID;
    ]]>
  </Command2>
</MySection333>

實現(xiàn)代碼如下:

public class MySection3 : ConfigurationSection
{
  [ConfigurationProperty("Command1", IsRequired = true)]
  public MyTextElement Command1
  {
    get { return (MyTextElement)this["Command1"]; }
  }

  [ConfigurationProperty("Command2", IsRequired = true)]
  public MyTextElement Command2
  {
    get { return (MyTextElement)this["Command2"]; }
  }
}

public class MyTextElement : ConfigurationElement
{
  protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
  {
    CommandText = reader.ReadElementContentAs(typeof(string), null) as string;
  }
  protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey)
  {
    if( writer != null )
      writer.WriteCData(CommandText);
    return true;
  }

  [ConfigurationProperty("data", IsRequired = false)]
  public string CommandText
  {
    get { return this["data"].ToString(); }
    set { this["data"] = value; }
  }
}

小結(jié):

1. 在實現(xiàn)上大體可參考MySection2,

2. 每個ConfigurationElement由我們來控制如何讀寫XML,也就是要重載方法SerializeElement,DeserializeElement

config文件 - Collection

<MySection444>
  <add key="aa" value="11111"></add>
  <add key="bb" value="22222"></add>
  <add key="cc" value="33333"></add>
</MySection444>

這種類似的配置方式,在ASP.NET的HttpHandler, HttpModule中太常見了,想不想知道如何實現(xiàn)它們? 代碼如下:

小結(jié):

1. 為每個集合中的參數(shù)項創(chuàng)建一個從ConfigurationElement繼承的派生類,可參考MySection1

2. 為集合創(chuàng)建一個從ConfigurationElementCollection繼承的集合類,具體在實現(xiàn)時主要就是調(diào)用基類的方法。

3. 在創(chuàng)建ConfigurationSection的繼承類時,創(chuàng)建一個表示集合的屬性就可以了,注意[ConfigurationProperty]的各參數(shù)。

config文件 - 讀與寫

前面我逐個介紹了4種自定義的配置節(jié)點的實現(xiàn)類,下面再來看一下如何讀寫它們。

讀取配置參數(shù):

MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111");
txtUsername1.Text = mySectioin1.UserName;
txtUrl1.Text = mySectioin1.Url;


MySection2 mySectioin2 = (MySection2)ConfigurationManager.GetSection("MySection222");
txtUsername2.Text = mySectioin2.Users.UserName;
txtUrl2.Text = mySectioin2.Users.Password;


MySection3 mySection3 = (MySection3)ConfigurationManager.GetSection("MySection333");
txtCommand1.Text = mySection3.Command1.CommandText.Trim();
txtCommand2.Text = mySection3.Command2.CommandText.Trim();


MySection4 mySection4 = (MySection4)ConfigurationManager.GetSection("MySection444");
txtKeyValues.Text = string.Join("\r\n",
            (from kv in mySection4.KeyValues.Cast<MyKeyValueSetting>()
             let s = string.Format("{0}={1}", kv.Key, kv.Value)
             select s).ToArray());

小結(jié):在讀取自定節(jié)點時,我們需要調(diào)用ConfigurationManager.GetSection()得到配置節(jié)點,并轉(zhuǎn)換成我們定義的配置節(jié)點類,然后就可以按照強類型的方式來訪問了。

寫配置文件:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

MySection1 mySectioin1 = config.GetSection("MySection111") as MySection1;
mySectioin1.UserName = txtUsername1.Text.Trim();
mySectioin1.Url = txtUrl1.Text.Trim();

MySection2 mySection2 = config.GetSection("MySection222") as MySection2;
mySection2.Users.UserName = txtUsername2.Text.Trim();
mySection2.Users.Password = txtUrl2.Text.Trim();

MySection3 mySection3 = config.GetSection("MySection333") as MySection3;
mySection3.Command1.CommandText = txtCommand1.Text.Trim();
mySection3.Command2.CommandText = txtCommand2.Text.Trim();

MySection4 mySection4 = config.GetSection("MySection444") as MySection4;
mySection4.KeyValues.Clear();

(from s in txtKeyValues.Lines
   let p = s.IndexOf('=')
   where p > 0
   select new MyKeyValueSetting { Key = s.Substring(0, p), Value = s.Substring(p + 1) }
).ToList()
.ForEach(kv => mySection4.KeyValues.Add(kv));

config.Save();

小結(jié):在修改配置節(jié)點前,我們需要調(diào)用ConfigurationManager.OpenExeConfiguration(),然后調(diào)用config.GetSection()在得到節(jié)點后,轉(zhuǎn)成我們定義的節(jié)點類型, 然后就可以按照強類型的方式來修改我們定義的各參數(shù)項,最后調(diào)用config.Save();即可。

注意:

1. .net為了優(yōu)化配置節(jié)點的讀取操作,會將數(shù)據(jù)緩存起來,如果希望使用修改后的結(jié)果生效,您還需要調(diào)用ConfigurationManager.RefreshSection(".....")

2. 如果是修改web.config,則需要使用 WebConfigurationManager

讀寫 .net framework中已經(jīng)定義的節(jié)點

前面一直在演示自定義的節(jié)點,那么如何讀取.net framework中已經(jīng)定義的節(jié)點呢?

假如我想讀取下面配置節(jié)點中的發(fā)件人。

<system.net>
  <mailSettings>
    <smtp from="Fish.Q.Li@newegg.com">
      <network />
    </smtp>
  </mailSettings>
</system.net>

讀取配置參數(shù):

SmtpSection section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
labMailFrom.Text = "Mail From: " + section.From;

寫配置文件:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

SmtpSection section = config.GetSection("system.net/mailSettings/smtp") as SmtpSection;
section.From = "Fish.Q.Li@newegg.com2";

config.Save();

xml配置文件

前面演示在config文件中創(chuàng)建自定義配置節(jié)點的方法,那些方法也只適合在app.config或者web.config中,如果您的配置參數(shù)較多, 或者打算將一些數(shù)據(jù)以配置文件的形式單獨保存,那么,直接讀寫整個XML將會更方便。 比如:我有一個實體類,我想將它保存在XML文件中,有可能是多條記錄,也可能是一條。

這次我來反過來說,假如我們先定義了XML的結(jié)構(gòu),是下面這個樣子的,那么我將怎么做呢?

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMyCommand xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <MyCommand Name="InsretCustomer" Database="MyTestDb">
  <Parameters>
   <Parameter Name="Name" Type="DbType.String" />
   <Parameter Name="Address" Type="DbType.String" />
  </Parameters>
  <CommandText>insret into .....</CommandText>
 </MyCommand>
</ArrayOfMyCommand>

對于上面的這段XML結(jié)構(gòu),我們可以在C#中先定義下面的類,然后通過序列化及反序列化的方式來實現(xiàn)對它的讀寫。

C#類的定義如下:

public class MyCommand
{
  [XmlAttribute("Name")]
  public string CommandName;

  [XmlAttribute]
  public string Database;

  [XmlArrayItem("Parameter")]
  public List<MyCommandParameter> Parameters = new List<MyCommandParameter>();

  [XmlElement]
  public string CommandText;
}

public class MyCommandParameter
{
  [XmlAttribute("Name")]
  public string ParamName;

  [XmlAttribute("Type")]
  public string ParamType;
}

有了這二個C#類,讀寫這段XML就非常容易了。以下就是相應(yīng)的讀寫代碼:

private void btnReadXml_Click(object sender, EventArgs e)
{
  btnWriteXml_Click(null, null);
  
  List<MyCommand> list = XmlHelper.XmlDeserializeFromFile<List<MyCommand>>(XmlFileName, Encoding.UTF8);

  if( list.Count > 0 )
    MessageBox.Show(list[0].CommandName + ": " + list[0].CommandText,
      this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

}

private void btnWriteXml_Click(object sender, EventArgs e)
{
  MyCommand command = new MyCommand();
  command.CommandName = "InsretCustomer";
  command.Database = "MyTestDb";
  command.CommandText = "insret into .....";
  command.Parameters.Add(new MyCommandParameter { ParamName = "Name", ParamType = "DbType.String" });
  command.Parameters.Add(new MyCommandParameter { ParamName = "Address", ParamType = "DbType.String" });

  List<MyCommand> list = new List<MyCommand>(1);
  list.Add(command);

  XmlHelper.XmlSerializeToFile(list, XmlFileName, Encoding.UTF8);
}

小結(jié):

1. 讀寫整個XML最方便的方法是使用序列化反序列化。

2. 如果您希望某個參數(shù)以Xml Property的形式出現(xiàn),那么需要使用[XmlAttribute]修飾它。

3. 如果您希望某個參數(shù)以Xml Element的形式出現(xiàn),那么需要使用[XmlElement]修飾它。

4. 如果您希望為某個List的項目指定ElementName,則需要[XmlArrayItem]

5. 以上3個Attribute都可以指定在XML中的映射別名。

6. 寫XML的操作是通過XmlSerializer.Serialize()來實現(xiàn)的。

7. 讀取XML文件是通過XmlSerializer.Deserialize來實現(xiàn)的。

8. List或Array項,請不要使用[XmlElement],否則它們將以內(nèi)聯(lián)的形式提升到當(dāng)前類,除非你再定義一個容器類。

XmlHelper的實現(xiàn)如下:

public static class XmlHelper
{
  private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
  {
    if( o == null )
      throw new ArgumentNullException("o");
    if( encoding == null )
      throw new ArgumentNullException("encoding");

    XmlSerializer serializer = new XmlSerializer(o.GetType());

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.NewLineChars = "\r\n";
    settings.Encoding = encoding;
    settings.IndentChars = "  ";

    using( XmlWriter writer = XmlWriter.Create(stream, settings) ) {
      serializer.Serialize(writer, o);
      writer.Close();
    }
  }

  /// <summary>
  /// 將一個對象序列化為XML字符串
  /// </summary>
  /// <param name="o">要序列化的對象</param>
  /// <param name="encoding">編碼方式</param>
  /// <returns>序列化產(chǎn)生的XML字符串</returns>
  public static string XmlSerialize(object o, Encoding encoding)
  {
    using( MemoryStream stream = new MemoryStream() ) {
      XmlSerializeInternal(stream, o, encoding);

      stream.Position = 0;
      using( StreamReader reader = new StreamReader(stream, encoding) ) {
        return reader.ReadToEnd();
      }
    }
  }

  /// <summary>
  /// 將一個對象按XML序列化的方式寫入到一個文件
  /// </summary>
  /// <param name="o">要序列化的對象</param>
  /// <param name="path">保存文件路徑</param>
  /// <param name="encoding">編碼方式</param>
  public static void XmlSerializeToFile(object o, string path, Encoding encoding)
  {
    if( string.IsNullOrEmpty(path) )
      throw new ArgumentNullException("path");

    using( FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write) ) {
      XmlSerializeInternal(file, o, encoding);
    }
  }

  /// <summary>
  /// 從XML字符串中反序列化對象
  /// </summary>
  /// <typeparam name="T">結(jié)果對象類型</typeparam>
  /// <param name="s">包含對象的XML字符串</param>
  /// <param name="encoding">編碼方式</param>
  /// <returns>反序列化得到的對象</returns>
  public static T XmlDeserialize<T>(string s, Encoding encoding)
  {
    if( string.IsNullOrEmpty(s) )
      throw new ArgumentNullException("s");
    if( encoding == null )
      throw new ArgumentNullException("encoding");

    XmlSerializer mySerializer = new XmlSerializer(typeof(T));
    using( MemoryStream ms = new MemoryStream(encoding.GetBytes(s)) ) {
      using( StreamReader sr = new StreamReader(ms, encoding) ) {
        return (T)mySerializer.Deserialize(sr);
      }
    }
  }

  /// <summary>
  /// 讀入一個文件,并按XML的方式反序列化對象。
  /// </summary>
  /// <typeparam name="T">結(jié)果對象類型</typeparam>
  /// <param name="path">文件路徑</param>
  /// <param name="encoding">編碼方式</param>
  /// <returns>反序列化得到的對象</returns>
  public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
  {
    if( string.IsNullOrEmpty(path) )
      throw new ArgumentNullException("path");
    if( encoding == null )
      throw new ArgumentNullException("encoding");

    string xml = File.ReadAllText(path, encoding);
    return XmlDeserialize<T>(xml, encoding);
  }
}

xml配置文件 - CDATA

在前面的演示中,有個不完美的地方,我將SQL腳本以普通字符串的形式輸出到XML中了:

<CommandText>insret into .....</CommandText>

顯然,現(xiàn)實中的SQL腳本都是比較長的,而且還可能會包含一些特殊的字符,這種做法是不可取的,好的處理方式應(yīng)該是將它以CDATA的形式保存, 為了實現(xiàn)這個目標(biāo),我們就不能直接按照普通字符串的方式來處理了,這里我定義了一個類 MyCDATA:

public class MyCDATA : IXmlSerializable
{
  private string _value;

  public MyCDATA() { }

  public MyCDATA(string value)
  {
    this._value = value;
  }

  public string Value
  {
    get { return _value; }
  }

  XmlSchema IXmlSerializable.GetSchema()
  {
    return null;
  }

  void IXmlSerializable.ReadXml(XmlReader reader)
  {
    this._value = reader.ReadElementContentAsString();
  }

  void IXmlSerializable.WriteXml(XmlWriter writer)
  {
    writer.WriteCData(this._value);
  }

  public override string ToString()
  {
    return this._value;
  }

  public static implicit operator MyCDATA(string text)
  {
    return new MyCDATA(text);
  }
}

我將使用這個類來控制CommandText在XML序列化及反序列化的行為,讓它寫成一個CDATA形式, 因此,我還需要修改CommandText的定義,改成這個樣子:

public MyCDATA CommandText;

最終,得到的結(jié)果是:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMyCommand xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <MyCommand Name="InsretCustomer" Database="MyTestDb">
  <Parameters>
   <Parameter Name="Name" Type="DbType.String" />
   <Parameter Name="Address" Type="DbType.String" />
  </Parameters>
  <CommandText><![CDATA[insret into .....]]></CommandText>
 </MyCommand>
</ArrayOfMyCommand>

xml文件讀寫注意事項

通常,我們使用使用XmlSerializer.Serialize()得到的XML字符串的開頭處,包含一段XML聲明元素:

<?xml version="1.0" encoding="utf-8"?>

由于各種原因,有時候可能不需要它。為了讓這行字符消失,我見過有使用正則表達(dá)式去刪除它的,也有直接分析字符串去刪除它的。 這些方法,要么浪費程序性能,要么就要多寫些奇怪的代碼??傊?,就是看起來很別扭。 其實,我們可以反過來想一下:能不能在序列化時,不輸出它呢? 不輸出它,不就達(dá)到我們期望的目的了嗎?

在XML序列化時,有個XmlWriterSettings是用于控制寫XML的一些行為的,它有一個OmitXmlDeclaration屬性,就是專門用來控制要不要輸出那行XML聲明的。 而且,這個XmlWriterSettings還有其它的一些常用屬性。請看以下演示代碼:

using( MemoryStream stream = new MemoryStream() ) {
  XmlWriterSettings settings = new XmlWriterSettings();
  settings.Indent = true;
  settings.NewLineChars = "\r\n";
  settings.OmitXmlDeclaration = true;
  settings.IndentChars = "\t";

  XmlWriter writer = XmlWriter.Create(stream, settings);

使用上面這段代碼,我可以:

1. 不輸出XML聲明。

2. 指定換行符。

3. 指定縮進(jìn)字符。

如果不使用這個類,恐怕還真的不能控制XmlSerializer.Serialize()的行為。

前面介紹了讀寫XML的方法,可是,如何開始呢? 由于沒有XML文件,程序也沒法讀取,那么如何得到一個格式正確的XML呢? 答案是:先寫代碼,創(chuàng)建一個要讀取的對象,隨便輸入一些垃圾數(shù)據(jù),然后將它寫入XML(反序列化), 然后,我們可以參考生成的XML文件的具體格式,或者新增其它的節(jié)點(列表), 或者修改前面所說的垃圾數(shù)據(jù),最終得到可以使用的,有著正確格式的XML文件。

配置參數(shù)的建議保存方式

經(jīng)常見到有很多組件或者框架,都喜歡把配置參數(shù)放在config文件中, 那些設(shè)計者或許認(rèn)為他們的作品的參數(shù)較復(fù)雜,還喜歡搞自定義的配置節(jié)點。 結(jié)果就是:config文件中一大堆的配置參數(shù)。最麻煩的是:下次其它項目還要使用這個東西時,還得繼續(xù)配置!

.net一直提倡XCOPY,但我發(fā)現(xiàn)遵守這個約定的組件或者框架還真不多。 所以,我想建議大家在設(shè)計組件或者框架的時候:

1. 請不要把你們的參數(shù)放在config文件中,那種配置真的不方便【復(fù)用】。

2. 能不能同時提供配置文件以及API接口的方式公開參數(shù),由用戶來決定如何選擇配置參數(shù)的保存方式。

config文件與XML文件的差別

從本質(zhì)上說,config文件也是XML文件,但它們有一點差別,不僅僅是因為.net framework為config文件預(yù)定義了許多配置節(jié)。 對于ASP.NET應(yīng)用程序來說,如果我們將參數(shù)放在web.config中,那么,只要修改了web.config,網(wǎng)站也將會重新啟動, 此時有一個好處:我們的代碼總是能以最新的參數(shù)運行。另一方面,也有一個壞處:或許由于種種原因,我們并不希望網(wǎng)站被重啟, 畢竟重啟網(wǎng)站會花費一些時間,這會影響網(wǎng)站的響應(yīng)。 對于這個特性,我只能說,沒有辦法,web.config就是這樣。

然而,當(dāng)我們使用XML時,顯然不能直接得到以上所說的特性。因為XML文件是由我們自己來維護(hù)的。

到這里,您有沒有想過:我如何在使用XML時也能擁有那些優(yōu)點呢?

我希望在用戶修改了配置文件后,程序能立刻以最新的參數(shù)運行,而且不用重新網(wǎng)站。

本文的所有示例代碼可以點擊此處下載。demo

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • asp.net core 實現(xiàn)一個簡單的倉儲的方法

    asp.net core 實現(xiàn)一個簡單的倉儲的方法

    本篇文章主要介紹了asp.net core 實現(xiàn)一個簡單的倉儲的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • 云服務(wù)器下搭建ASP.NET Core環(huán)境

    云服務(wù)器下搭建ASP.NET Core環(huán)境

    本文給大家分享的是在云服務(wù)器上搭建ASP.NET Core環(huán)境以及成功運行官網(wǎng)DEMO的教程,十分的細(xì)致全面,有需要的小伙伴可以參考下。
    2016-07-07
  • 關(guān)閉子頁面刷新父頁面中部分控件數(shù)據(jù)的方法

    關(guān)閉子頁面刷新父頁面中部分控件數(shù)據(jù)的方法

    關(guān)閉子頁面刷新父頁面中部分控件數(shù)據(jù),具體的實現(xiàn)代碼如下,感興趣的朋友可以參考下哈
    2013-05-05
  • log4net配置和使用方法分享

    log4net配置和使用方法分享

    這篇文章主要介紹了log4net配置和使用方法,大家參考使用吧
    2014-01-01
  • Asp.net中防止用戶多次登錄的方法

    Asp.net中防止用戶多次登錄的方法

    在web開發(fā)時,有的系統(tǒng)要求同一個用戶在同一時間只能登錄一次,也就是如果一個用戶已經(jīng)登錄了,在退出之前如果再次登錄的話需要報錯。
    2008-08-08
  • ASP.NET中Cookie的用法實例分析

    ASP.NET中Cookie的用法實例分析

    這篇文章主要介紹了ASP.NET中Cookie的用法,實例分析了在asp.net中針對cookie的設(shè)置、添加及讀取等常用操作技巧,非常簡單實用,需要的朋友可以參考下
    2015-08-08
  • ASP.NET Core中使用多環(huán)境

    ASP.NET Core中使用多環(huán)境

    這篇文章介紹了ASP.NET Core中使用多環(huán)境的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • asp.net單文件帶進(jìn)度條上傳的解決方案

    asp.net單文件帶進(jìn)度條上傳的解決方案

    本文介紹的asp.net單文件帶進(jìn)度條上傳,不屬于任務(wù)控件,也不是flash類型的上傳,完全是asp.net、js、css實現(xiàn)上傳,需要的朋友可以參考下
    2015-09-09
  • asp.net 簡單實現(xiàn)禁用或啟用頁面中的某一類型的控件

    asp.net 簡單實現(xiàn)禁用或啟用頁面中的某一類型的控件

    最近在一個winform項目中碰到的一個功能,勾選一個checkbox后窗體中的其他控件不可用。由此想到asp.net項目中有時候也要用到這種功能。
    2009-11-11
  • WPF的數(shù)據(jù)綁定詳細(xì)介紹

    WPF的數(shù)據(jù)綁定詳細(xì)介紹

    數(shù)據(jù)綁定:是應(yīng)用程序 UI 與業(yè)務(wù)邏輯之間建立連接的過程。 如果綁定正確設(shè)置并且數(shù)據(jù)提供正確通知,則當(dāng)數(shù)據(jù)的值發(fā)生更改時,綁定到數(shù)據(jù)的視覺元素會自動反映更改。 數(shù)據(jù)綁定可能還意味著如果視覺元素中數(shù)據(jù)的外部表現(xiàn)形式發(fā)生更改,則基礎(chǔ)數(shù)據(jù)可以自動更新以反映更改。
    2013-03-03

最新評論