原链接:http://www.cnblogs.com/sashow/archive/2005/09/26/244426.html

 

在做 web 项目的时候,我一直在用 web.config ,觉得这个东西实在不错。偶然间发现,原来 winform 项目也有一个类似于 web.config 的文件——app.config,和呵,不胜欣喜!

一、添加app.config
        方法一:手工添加
         要添加这个文件很简单,执行如下操作就可以了:在开发环境中选择“项目”——>“添加新项”——>“XML 文件”,输入xml 文件的名称为 app.config。
        然后就可以如同 web.config 一样,编辑 app.config 文件,以及在应用程序中读、写该配置文件。
        重新编译项目,在应用程序的运行目录下会生成一个 app.config 的副本,名称为:程序名.exe.config。
        方法二:系统自动添加
        假设我们现在要使用 app.config 来动态配置一个 label 的 text 属性,那么,在label的属性窗口中选择如下图的属性进行配置,那么就可以让系统自动添加一个 app.config 的文件,呵呵,很省事的了。
winform 程序的配置文件——App.config(转)

二、编辑和使用app.config
        1、增加自定义的键值
        这个当然是增加<appSettings>标签了。下面给个例子:

winform 程序的配置文件——App.config(转)<?xml version="1.0" encoding="utf-8"?> 
winform 程序的配置文件——App.config(转)
<configuration>
winform 程序的配置文件——App.config(转)    
<appSettings>
winform 程序的配置文件——App.config(转)        
<add key="port" value="5450" />
winform 程序的配置文件——App.config(转)        
<add key="Thread" value="20" />
winform 程序的配置文件——App.config(转)    
</appSettings>
winform 程序的配置文件——App.config(转)
<configuration>
        在这里我设置了一个叫做 port 和 Thread 的键,用来表示通讯端口和允许的最大线程数。
        根据应用的需要,我们可以添加许多需要动态配置的信息,如数据库连接字符串等。

        2、编辑系统原有的属性
        在下面的代码中,我配置了系统调试信息,这个东西挺不错的,可以将系统运行时输出的调试信息放置到一个文件。在我们使用 try ... catch 的时候,将 catch 到的信息输出给用户并不理想,因为用户看到一大堆的错误信息会感到很头痛,他们只希望知道操作成功还是没有成功。所以,将运行时的错误信息放置到文件是不错的选择。代码如下:
winform 程序的配置文件——App.config(转)<?xml version="1.0" encoding="utf-8"?> 
winform 程序的配置文件——App.config(转)
<configuration>
winform 程序的配置文件——App.config(转)
<system.diagnostics>
winform 程序的配置文件——App.config(转)    
<switches>
winform 程序的配置文件——App.config(转)        
<add name="MagicTraceSwitch" value="3" />
winform 程序的配置文件——App.config(转)    
</switches>
winform 程序的配置文件——App.config(转)    
<trace autoflush="true" indentsize="4">
winform 程序的配置文件——App.config(转)        
<listeners>
winform 程序的配置文件——App.config(转)           
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="myListener.log" />
winform 程序的配置文件——App.config(转)           
<remove type="System.Diagnostics.DefaultTraceListener" /> 
winform 程序的配置文件——App.config(转)        
</listeners>
winform 程序的配置文件——App.config(转)    
</trace>
winform 程序的配置文件——App.config(转)
</system.diagnostics>
winform 程序的配置文件——App.config(转)
</configuration>
测试代码如下:

 1winform 程序的配置文件——App.config(转)using System;
 2winform 程序的配置文件——App.config(转)using System.Drawing;
 3winform 程序的配置文件——App.config(转)using System.Collections;
 4winform 程序的配置文件——App.config(转)using System.ComponentModel;
 5winform 程序的配置文件——App.config(转)using System.Windows.Forms;
 6winform 程序的配置文件——App.config(转)using System.Data;
 7winform 程序的配置文件——App.config(转)
 8winform 程序的配置文件——App.config(转)using System.Diagnostics ;
 9winform 程序的配置文件——App.config(转)using System.Configuration ;
10winform 程序的配置文件——App.config(转)
11winform 程序的配置文件——App.config(转)namespace AppTest
12

相关文章: