C#Winform中儲存配置資訊App.Config的類操作日誌操作
阿新 • • 發佈:2019-02-14
C#Winform中儲存配置資訊App.Config的類操作:
新增引用:System.Configuration;
/// <summary>
/// 配置資訊維護
/// </summary>
public class AppConfig
{
public static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// 獲取配置值
/// </summary>
/// <param name="key">配置標識</param>
/// <returns></returns>
public static string GetValue(string key)
{
string result = string.Empty;
if (config.AppSettings.Settings[key] != null)
result = config.AppSettings.Settings[key].Value;
return result;
}
/// <summary>
/// 修改或增加配置值
/// </summary>
/// <param name="key">配置標識</param>
/// <param name="value">配置值</param>
public static void SetValue(string key, string value)
{
if (config.AppSettings.Settings[key] != null)
config.AppSettings.Settings[key].Value = value;
else
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified);
}
/// <summary>
/// 刪除配置值
/// </summary>
/// <param name="key">配置標識</param>
public static void DeleteValue(string key)
{
config.AppSettings.Settings.Remove(key);
}
}
日誌操作:
/// <summary> /// 日誌操作 /// </summary> public class LogAccess { /// <summary> /// 寫入日誌 /// </summary> /// <param name="logContent"></param> public static void WriteLog(string logContent) { try { string logName = DateTime.Now.ToString("yyyy-MM-dd") + ".log"; FileStream fileStream = new FileStream(logName, FileMode.Append); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine(string.Format("{0}錯誤:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffffff"), logContent)); writer.Close(); fileStream.Close(); } catch { } } }