Winform/ASP.NET app.config 配置文件的使用

引言:

在日常开发中我们习惯将在程序的配置信息存到XML文件中,但是在代码中读写XML文件并不是很方便。Winform/ASP.NET 框架内app.config文件大家一定不陌生,在Visual Studio中一些自动生成配置信息也在保存在此文件中, 添加app.config到项目,如下图:

 

 通过ConfigurationManager类对app.config文件读写,在编码效率上远高于直接对XML文件读写。

注意ConfigurationManager类需要导入包System.Configuration.ConfigurationManager:

在app.config文件中创建内置节点<appSettings>:

上图中 <appSettings> 节点标签为内置标签,请注意首字母小写,通过ConfigurationManager.AppSettings["UserName"]可快速定位到<appSettings>节点下的子节点。

读取节点:

        private void btn_Read_Click(object sender, EventArgs e)
        {
            string userName = ConfigurationManager.AppSettings["UserName"];//读取<appSettings>节点下UserName的值
            label_Name.Text = "UserName:"+ userName;

        }

 更新节点:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;

app.Settings["UserName"].Value = "Jack";//更新UserName的值
config.Save(ConfigurationSaveMode.Modified);//保存

 增加节点:

app.Settings.Add("nodeName", "nodeValue"); 

在exe文件的路径下会生成后缀为config的配置文件,在记事本中打开此文件,即可对程序配置信息进行管理:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 WinForm 程序中使用 WebRequest 发送 HTTP GET 请求,你可以按照以下步骤操作: 1. 引用 System.Net 命名空间。 ```csharp using System.Net; ``` 2. 创建一个 WebRequest 对象,并设置请求的 URL。 ```csharp WebRequest request = WebRequest.Create("http://61.155.88.154:7032"); ``` 3. 发送 HTTP GET 请求,并获取响应。 ```csharp WebResponse response = request.GetResponse(); ``` 4. 读取响应内容,并关闭响应。 ```csharp Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string responseBody = reader.ReadToEnd(); response.Close(); ``` 下面是一个完整的示例代码: ```csharp using System; using System.Net; using System.IO; namespace WinFormWebRequestDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { WebRequest request = WebRequest.Create("http://61.155.88.154:7032"); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string responseBody = reader.ReadToEnd(); response.Close(); Console.WriteLine(responseBody); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } ``` 这个示例使用 WebRequest 类发送一个 HTTP GET 请求,并将响应内容输出到控制台。注意,这个示例是在 UI 线程中执行的,如果你要在后台线程中发送请求,请使用异步方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值