zoukankan      html  css  js  c++  java
  • 使用ExeConfigurationFileMap读写配置文件

    使用ExeConfigurationFileMap读写配置文件

    using System;
    using System.IO;
    using System.Configuration;
    public class AppConfig
    {                
        
    public string LastLoginId
        {
            
    get { return this.GetItem("LastLoginId"); }
            
    set { this.SetItem("LastLoginId", value); }
        }

        
    private Configuration config;

        
    public AppConfig()
        {
            ExeConfigurationFileMap configMap 
    = new ExeConfigurationFileMap();
            configMap.ExeConfigFilename 
    = this.CreateConfig();
            
    this.config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
        }

        
    private string CreateConfig()
        {
            
    try
            {
                
    string configFile = AppDomain.CurrentDomain.BaseDirectory + @"app.config";
                
    if (!File.Exists(configFile))
                {
                    
    string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n</configuration>";
                    
    using (StreamWriter sw = new StreamWriter(configFile))
                    {
                        sw.Write(xml);
                    }
                }
                
    return configFile;
            }
            
    catch (Exception ex)
            {
                
    string msg = ex.Message;
                
    throw;
            }
        }

        
    private string GetItem(string item)
        {
            
    if (this.config.AppSettings.Settings[item] == null)
            {
                
    return string.Empty;
            }
            
    else
            {
                
    return this.config.AppSettings.Settings[item].Value;
            }
        }

        
    private void SetItem(string item, string value)
        {
            
    if (this.config.AppSettings.Settings[item] == null)
            {
                
    this.config.AppSettings.Settings.Add(item, value);
            }
            
    else
            {
                
    this.config.AppSettings.Settings[item].Value = value;
            }
            
    this.Save();
        }

        
    private void Save()
        {
            
    try
            {
                
    this.config.Save(ConfigurationSaveMode.Modified);
            }
            
    catch (Exception ex)
            {
                
    string msg = ex.Message;
                throw;
            }
        }
    }

     

  • 相关阅读:
    Linux 误卸载软件,所有命令不能用了咋办
    MySQL 全局锁和表锁
    MongoDB 基础
    MySQL 常见错误
    MySQL 锁信息和事务
    B2C电子商务平台概述及开发公司推荐
    O2O本地生活平台推荐
    OA办公系统哪个公司做的好
    集团企业OA系统选型推荐
    协同OA办公系统选型推荐
  • 原文地址:https://www.cnblogs.com/anjou/p/2068504.html
Copyright © 2011-2022 走看看