StreamWriter类
1、使用的命名空间是:System.IO;
2、用来将字符串写入文件。
常用方法:
WriteLine():写入文件,并且换行。
Write():多种重写方式,具体可以查VS文档。
Dispose():释放由 System.IO.StreamWriter 占用的非托管资源,还可以另外再释放托管资源。
Flush():清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。
Close():关闭流。
public static void WriteFailLog(string log)
{
String LogPath = "Fail_Log"; //文件夹名称
try
{
string filename = DateTime.Now.ToString("yyyyMMdd") + ".log"; //文件名称
//判断文件夹是否存在
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + LogPath))
{
//文件夹不存在,创建文件夹
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + LogPath);
}
//实例化一个文件,存在就追加(参数2true)或覆盖(参数2false),不存在就创建一个文件
StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + LogPath + "\\" + filename, true);
//写入数据,写入并换行
sw.WriteLine(log);
//关闭流
sw.Close();
}
catch
{
return;
}
}