阅读 414

WPF 项目中的App.config配置信息的读写操作

C# 测试读写配置信息

1. 添加引用

System.Configuration;

 

2. 在app.config文件添加配置参数信息

  

//如下的导出文件路径为配置的默认路径

  

在配置文件中设置默认导出的文件名和路径。

读取配置

后台代码添加引用:

using System.Configuration;

//1.读取配置信息

string exportFilePath = ConfigurationManager.AppSettings["ExportFilePath"];

Console.WriteLine(exportFilePath);

 

修改配置信息

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

cfa.AppSettings.Settings["ExportFilePath"].Value = “C:\\Test2.xlsx”;

//cfa.Save();

//或者

cfa.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings"); //刷新

创建Console项目演示,完整代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Configuration;

namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//1.读取配置信息 ExportFilePath
//Console.WriteLine(ReadConfigValue("ExportFilePath"));

//2. 写操作 C:\\Test2.xlsx
if(SetConfigValue("ExportFilePath","C:\\TestPath\\Test.xlsx"))
{
Console.WriteLine("写配置成功!");
}

}

static string ReadConfigValue(string keyName)
{
string exportFilePath = ConfigurationManager.AppSettings[keyName];
return exportFilePath;
}


static bool SetConfigValue(string keyName, string value)
{
try
{
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings[keyName].Value = value;
//cfa.Save();
//或者
cfa.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings"); //刷新

return true;
}
catch (Exception)
{
return false;
}
}
}
}

————————————————
版权声明:本文为CSDN博主「flysh05」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/flysh13/article/details/120080652

原文:https://www.cnblogs.com/flysh/p/15222939.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐