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;
            }
        }
    }

     

  • 相关阅读:
    window.location.href无法跳转的解决办法
    HTTP 错误 405.0
    C# 浅拷贝与深拷贝
    C# .ToString() 格式化
    深入理解AsyncTask
    【转】Android子线程真的不能更新UI么
    深入理解Activity的启动模式
    Android7.0,剪裁后提示“无法保存经过裁剪的图片”
    Android工程改包名
    javah命令,提示“找不到类文件”
  • 原文地址:https://www.cnblogs.com/anjou/p/2068504.html
Copyright © 2011-2022 走看看