今天做了日志文件读写,使用方法FileStream ,StreamWriter ,File
//异常处理
public static bool GeException(string strMessage, string strName)
{
string time = System.DateTime.Now.ToString();
string strPathName = System.DateTime.Now.ToShortDateString() + "_" + strName + "_Error__Log.txt";
//指定路径
string strPath = "C:\\EWJAR_LoG";
if (!Directory.Exists(strPath))
{
DirectoryInfo di = Directory.CreateDirectory(strPath);
}
strPathName = strPath + "\\" + strPathName;
WirteFile(strPathName, strMessage);
////如果文件a.txt存在就打开,不存在就新建 .append 是追加写
//FileStream fst = new FileStream(strPathName, FileMode.Append);
////写数据到a.txt格式
//StreamWriter swt = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));
////写入
//swt.WriteLine(time + '\r' + "错误信息开始:" + strMessage);
//swt.Close();
//fst.Close();
return true;
}
/// <summary>
/// 判断文件否存在,不存在,创建,存在追加重写
/// </summary>
/// <param name="strPath">文绝对路径</param>
/// <param name="strMessage">消息</param>
public static void WirteFile(string strPath, string strMessage)
{
string time = System.DateTime.Now.ToString();
//判断文件的存在
if (File.Exists(strPath))
{
//存文件
//如果文件a.txt存在就打开,不存在就新建 .append 是追加写
FileStream fst = new FileStream(strPath, FileMode.Append);
//写数据到a.txt格式
StreamWriter swt = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));
//写入
swt.WriteLine(time + strMessage);
swt.Close();
fst.Close();
}
else
{
//不存在文件
FileStream fst = new FileStream(strPath, FileMode.CreateNew);
//写数据到a.txt格式
StreamWriter swt = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));
//写入
swt.WriteLine(time + strMessage);
swt.Close();
fst.Close();
}
}