您的位置:首页 > 其它

今天做了日志文件读写,使用方法FileStream ,StreamWriter ,File

2010-10-27 11:58 471 查看
//异常处理
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: