App.config中AppSettings的读写
using System;
using System.Configuration;
using System.IO;
namespace ScanBind
{
public class FileHelper
{
#region 文件的读写
public static string GetFileName()
{
string path = System.Environment.CurrentDirectory;
string fileName = DateTime.Now.ToString("yyyyMMdd")+".txt";
return fileName;
}
public static void AppendText(string data)
{
FileInfo fi = new FileInfo(GetFileName());
StreamWriter sw = fi.AppendText();
if (!fi.Exists)
{
//文件不存在时先创建
FileStream fs = fi.Create();
fs.Close();
fs.Dispose();
}
sw.WriteLine(data);
sw.Flush();
sw.Close();
}
public static string ReadText()
{
StreamReader sr = new StreamReader(GetFileName());
string data = "";
while (!sr.EndOfStream)
{
string str = sr.ReadLine();
data += str + System.Environment.NewLine;
}
sr.Close();
return data;
}
#endregion
#region App.config中AppSettings的读写
public static string GetConfigValue(string key)
{
try
{
return ConfigurationManager.AppSettings[key].ToString();
}
catch
{
//获取失败默认2
return "2";
}
}
public static bool SetConfigValue(string key, string value)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
config.AppSettings.Settings[key].Value = value;
else
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
catch
{
//设置失败
return false;
}
}
#endregion
}
}