>  기사  >  백엔드 개발  >  .net에서 구성 파일을 읽고 쓰는 다양한 방법에 대한 자세한 설명

.net에서 구성 파일을 읽고 쓰는 다양한 방법에 대한 자세한 설명

高洛峰
高洛峰원래의
2016-12-24 13:19:531143검색

오늘은 .net에서 구성 파일을 읽고 쓰는 다양한 방법에 대해 이야기하겠습니다. 이번 블로그에서는 다양한 구성 파일의 읽기 및 쓰기 작업을 소개하겠습니다. 내용이 비교적 직관적이기 때문에 빈 이론은 많지 않고 실제 데모 코드만 있으며 실제 개발에서 다양한 시나리오를 재현하는 것이 목적입니다. 모두가 좋아하길 바랍니다.

일반적으로 .NET 개발 과정에서 우리는 구성 파일과 xml 파일이라는 두 가지 유형의 구성 파일을 접하게 됩니다. 오늘의 블로그 예제에서는 이 두 가지 범주의 구성 파일에 대한 다양한 작업도 소개합니다. config 파일에서는 appSetting 사용법을 소개하기보다는 사용자 정의 구성 노드를 직접 생성하는 방법을 주로 보여드리겠습니다.

참고: 이 문서에 언급된 구성 파일은 일반 XML 파일이 아닌 app.config 또는 web.config를 구체적으로 나타냅니다. 이러한 유형의 구성 파일에서는 .net 프레임워크가 일부 구성 노드를 정의했기 때문에 직렬화를 통해 단순히 읽고 쓸 수는 없습니다.

구성 파일 - 사용자 정의 구성 노드

사용자 정의 구성 노드가 필요한 이유는 무엇입니까?

실제로 많은 사람들이 구성 파일을 사용할 때 appSetting을 직접 사용하고 여기에 모든 구성 매개변수를 입력하는 것이 좋지만 매개변수가 너무 많으면 이 접근 방식이 작동하지 않습니다. 또한 명확하게 노출됩니다. appSetting의 구성 매개변수 항목은 키 이름으로만 액세스할 수 있고 복잡한 계층적 노드를 지원할 수 없으며 강력한 유형을 지원하지 않습니다. 이 세트만 사용하므로 다음을 발견할 수 있습니다. 합쳐져라!

이 문제를 해결하고 싶으신가요? 사용자 정의 구성 노드는 이 문제를 해결하는 실현 가능한 방법입니다.

먼저 app.config 또는 web.config에 사용자 정의 구성 노드를 추가하는 방법을 살펴보겠습니다. 이번 블로그에서는 노드 구성을 사용자 정의하는 4가지 방법을 소개하겠습니다. 최종 구성 파일은 다음과 같습니다.

<?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.jb51.net/"></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>

동시에 모든 샘플 코드도 제공합니다(다운로드 가능). 기사 끝) 데모 프로그램의 인터페이스는 다음과 같습니다.

config 파일 - 속성

먼저 가장 간단한 사용자 정의 노드를 살펴보겠습니다. 각 구성 값은 속성의 형태로 존재합니다. :

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

구현 코드는 다음과 같습니다.

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; }
  }
}

요약:

1 . ConfigurationSection을 기본 클래스로 사용하여 클래스를 사용자 정의합니다. 각 속성은 [ConfigurationProperty]를 사용하여 추가되어야 합니다. ConfigurationProperty의 생성자에 전달된 이름 문자열은 구성 파일에서 각 매개변수의 속성 이름을 나타내는 데 사용됩니다.

2. 속성의 값을 읽고 쓰려면 기본 클래스에 저장되어 있는 []을 호출해야 합니다. 직접 저장하도록 필드를 설계하지 마세요.

3. 구문 분석할 구성 노드를 사용하려면 f0c345cb8609a7447fbc7220c375eedc에 등록해야 합니다: 0e8695a814a38e2f86def8fe1118e99b , 그리고 name="MySection111"은 af8cee00c51cd6e0e68b60333e386f8f과 일치해야 합니다.

참고: 다음으로 세 가지 다른 구성 노드를 소개합니다. 조금 더 복잡하지만 일부 기본 사항은 이 노드와 동일하므로 나중에 설명을 반복하지 않겠습니다.

config file-Element

더 복잡한 항목을 살펴보겠습니다. 각 구성 항목은 XML 요소의 형태로 존재합니다.

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

구현 코드는 다음과 같습니다.

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; }
  }
}

요약:

1. to ConfigurationSection 기본 클래스로 [ConfigurationProperty]

로 각 속성을 추가해야 합니다. 2. 유형도 사용자 정의되며 특정 구성 속성은 ConfigurationElement의 상속 클래스에 작성됩니다.

구성 파일 - CDATA

때때로 구성 매개변수에 SQL 스크립트 또는 HTML 코드와 같은 긴 텍스트가 포함된 경우 CDATA 노드가 필요합니다. 두 개의 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>

구현 코드는 다음과 같습니다.

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; }
  }
}

요약:

1. 구현 방법은 일반적으로 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에서 구성 방법은 너무 일반적입니다. 구현 방법을 알고 싶으십니까? 코드는 다음과 같습니다.

요약:

1. 컬렉션의 각 매개변수 항목에 대해 ConfigurationElement를 상속하는 파생 클래스를 만듭니다. MySection1

2. 컬렉션에 대한 ConfigurationElementCollection을 상속하는 컬렉션 클래스를 만듭니다. 구체적인 구현은 기본 클래스 메서드를 호출하는 것입니다.


3. ConfigurationSection의 상속 클래스를 생성할 때 컬렉션을 나타내는 속성을 생성하면 됩니다. [ConfigurationProperty]의 매개변수에 주의하세요.

config 파일 - 읽기 및 쓰기

앞서 4가지 사용자 정의 구성 노드의 구현 클래스를 하나씩 읽고 쓰는 방법을 살펴보겠습니다.

구성 매개변수 읽기:

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());

요약: 사용자 정의 노드를 읽을 때 ConfigurationManager.GetSection()을 호출해야 합니다. 구성 노드를 정의한 구성 노드 클래스로 변환한 다음 강력한 형식의 방식으로 액세스합니다.

写配置文件:

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(&#39;=&#39;)
   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();

   

小结:在修改配置节点前,我们需要调用ConfigurationManager.OpenExeConfiguration(),然后调用config.GetSection()在得到节点后,转成我们定义的节点类型, 然后就可以按照强类型的方式来修改我们定义的各参数项,最后调用config.Save();即可。

注意:

1. .net为了优化配置节点的读取操作,会将数据缓存起来,如果希望使用修改后的结果生效,您还需要调用ConfigurationManager.RefreshSection(".....")

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

读写 .net framework中已经定义的节点

前面一直在演示自定义的节点,那么如何读取.net framework中已经定义的节点呢?

假如我想读取下面配置节点中的发件人。

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

   

读取配置参数:

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文件中创建自定义配置节点的方法,那些方法也只适合在app.config或者web.config中,如果您的配置参数较多, 或者打算将一些数据以配置文件的形式单独保存,那么,直接读写整个XML将会更方便。 比如:我有一个实体类,我想将它保存在XML文件中,有可能是多条记录,也可能是一条。

这次我来反过来说,假如我们先定义了XML的结构,是下面这个样子的,那么我将怎么做呢? 

<?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结构,我们可以在C#中先定义下面的类,然后通过序列化及反序列化的方式来实现对它的读写。

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就非常容易了。以下就是相应的读写代码:

   
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);
}

   

小结:

1. 读写整个XML最方便的方法是使用序列化反序列化。

2. 如果您希望某个参数以Xml Property的形式出现,那么需要使用[XmlAttribute]修饰它。

3. 如果您希望某个参数以Xml Element的形式出现,那么需要使用[XmlElement]修饰它。

4. 如果您希望为某个List的项目指定ElementName,则需要[XmlArrayItem]

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

6. 写XML的操作是通过XmlSerializer.Serialize()来实现的。

7. 读取XML文件是通过XmlSerializer.Deserialize来实现的。

8. List或Array项,请不要使用[XmlElement],否则它们将以内联的形式提升到当前类,除非你再定义一个容器类。

XmlHelper的实现如下: 

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>序列化产生的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">结果对象类型</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">结果对象类型</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>

   

显然,现实中的SQL脚本都是比较长的,而且还可能会包含一些特殊的字符,这种做法是不可取的,好的处理方式应该是将它以CDATA的形式保存, 为了实现这个目标,我们就不能直接按照普通字符串的方式来处理了,这里我定义了一个类 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;

   

最终,得到的结果是:

<?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"?>

   

由于各种原因,有时候可能不需要它。为了让这行字符消失,我见过有使用正则表达式去删除它的,也有直接分析字符串去删除它的。 这些方法,要么浪费程序性能,要么就要多写些奇怪的代码。总之,就是看起来很别扭。 其实,我们可以反过来想一下:能不能在序列化时,不输出它呢? 不输出它,不就达到我们期望的目的了吗?

在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. 指定缩进字符。

如果不使用这个类,恐怕还真的不能控制XmlSerializer.Serialize()的行为。

XML을 읽고 쓰는 방법은 앞서 소개했는데 어떻게 시작해야 할까요? XML 파일이 없기 때문에 프로그램이 이를 읽을 수 없습니다. 그러면 올바른 형식의 XML을 얻는 방법은 무엇입니까? 대답은 먼저 코드를 작성하고, 읽을 개체를 만들고, 일부 정크 데이터를 입력한 다음 이를 XML에 쓰는 것입니다(역직렬화). 그런 다음 생성된 XML 파일의 특정 형식을 참조하거나 다른 노드를 추가할 수 있습니다. (목록) 또는 위에서 언급한 정크 데이터를 수정하여 최종적으로 올바른 형식의 사용 가능한 XML 파일을 얻습니다.

구성 매개변수를 저장하는 권장 방법

구성 매개변수를 구성 파일에 넣는 것을 좋아하는 구성요소나 프레임워크가 많은 경우 이러한 디자이너는 자신의 작업의 매개변수가 다음과 같다고 생각할 수 있습니다. 더 복잡하고 사용자 정의 구성 노드를 만드는 것을 좋아합니다. 결과는 구성 파일에 많은 구성 매개변수가 있다는 것입니다. 가장 골치 아픈 점은 다음 번에 다른 프로젝트에서 이 기능을 사용하려면 계속해서 구성해야 한다는 것입니다!

.net은 항상 XCOPY를 옹호해 왔지만 이 규칙을 준수하는 구성 요소나 프레임워크가 많지 않다는 것을 알았습니다. 따라서 컴포넌트나 프레임워크를 설계할 때 다음을 제안하고 싶습니다.

1. 그런 구성은 정말 불편합니다[재사용].

2. 매개변수를 구성 파일과 API 인터페이스의 형태로 동시에 공개할 수 있는지 여부는 구성 매개변수를 저장하는 방법을 결정하는 것입니다.

구성 파일과 XML 파일의 차이점

기본적으로 구성 파일도 XML 파일이지만 약간 다릅니다. .net 프레임워크가 많은 구성 파일 구성 섹션을 미리 정의하기 때문만은 아닙니다. ASP.NET 응용 프로그램의 경우 web.config에 매개 변수를 넣으면 web.config가 수정되는 한 웹 사이트가 다시 시작됩니다. 이때 이점이 있습니다. 코드는 항상 최신 매개 변수로 업데이트될 수 있습니다. 달리다. 반면에 단점도 있습니다. 아마도 여러 가지 이유로 웹사이트를 다시 시작하는 것을 원하지 않을 것입니다. 결국 웹사이트를 다시 시작하는 데 시간이 걸리고 이는 웹사이트의 응답에 영향을 미칠 것입니다. 이 기능에 대해서는 방법이 없다고밖에 말씀드릴 수 없습니다. web.config는 이렇습니다.

그러나 XML을 사용하면 위의 기능을 직접 얻을 수 없다는 것이 분명합니다. XML 파일은 자체적으로 유지 관리되기 때문입니다.

이 시점에서 XML을 사용할 때 어떻게 이러한 이점을 얻을 수 있는지 생각해 본 적이 있습니까?

사용자가 구성 파일을 수정한 후 웹사이트를 다시 방문할 필요 없이 즉시 최신 매개변수로 프로그램을 실행할 수 있기를 바랍니다.

이 기사의 모든 샘플 코드는 여기에서 다운로드할 수 있습니다. 데모

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다.


.net에서 구성 파일을 읽고 쓰는 다양한 방법에 대한 자세한 설명은 PHP 중국어 웹사이트의 관련 기사를 참고하세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.