用户名和密码写在配置文件里面

最近写一个小工具,把读取Excel文件数据上传到SharePoint上,写完之后需要写个配置文件来保存一些需要用户自己设置的东西,现在将其记录下来

1.自己建一个config文件,里面的内容如下,这里以用户名和密码为例



2.读取config里面的内容

XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = null;
xmlDoc.Load("config.txt");//配置文件的路径
xmlElement = xmlDoc.SelectSingleNode("mySelfSet") as XmlElement;
string userName=xmlElement.GetAttribute("userName");
string passWord= xmlElement.GetAttribute("passWord");
                

3.这样每次只需要更改配置文件里面的值就可以得到需要提前设置的属性了

后来发现VS里面建好项目以后自带一个App.config文件,也可以将属性写在里面

1.App.config文件内容如下



     
        
    
    
        
        
    

2.读取里面数据之前,project得加一个system.configuration.dll引用,用系统内提供的一个类进行操作,就省去了上面使用XmlDocument进行读取操作

3.读取数据

string userName=ConfigrutionManager.AppSettings["userName"];
string passWord=ConfigrutionManager.AppSettings["passWord"];

4.关于App.config文件读取添加删除更新操作,这里就简单记录一下,看api的名字就很容易懂了,参考来源:MSDN ConfigurationManager Class

Configuration config=ConfigurationManager.OpenExeConfiguration(ConfigurationUser.None);
//添加
config.AppSettings.Settings.Add(key,value);
//删除
config.AppSettings.Settings.Remove(key);
//取值
string str=config.AppSettings.Settings[key].Value;
//赋值
config.AppSettings.Settings[key]=str;

C#新手,邮箱[email protected],欢迎讨论

你可能感兴趣的:(闲杂)