写日志 log 到文件夹
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DBUtility
{
public class FileHelper
{
public static void writeLog(string strSQL)
{
try
{
string strFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string strPath = "d:/log/";
string strAllPath = strPath + strFileName;
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
if (File.Exists(strAllPath))
{
StreamWriter sw = new StreamWriter(strAllPath, true);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + strSQL); // 写入Hello World
sw.Close(); //关闭文件
}
else
{
FileStream fs = new FileStream(strAllPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + strSQL); // 写入Hello World
sw.Close(); //关闭文件
fs.Close();
}
}
catch (Exception ex) { }
finally { }
}
}
}
2---------------------------
public static void SaveInfoToTxtFile(string info)
{
//如果不存在Log文件夹就创建文件夹
if (Directory.Exists(@"e:\iis\publish\Log") == false)
{
Directory.CreateDirectory(@"e:\iis\publish\Log");
}
string fileName = @"e:\iis\publish\Log\" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
if (!File.Exists(fileName))
{
File.Create(fileName);
}
try
{
using (StreamWriter sWriter = File.AppendText(fileName))
{
sWriter.WriteLine("sdfsdf");
sWriter.Flush();
}
}
catch (Exception err)
{
Console.WriteLine("\r\n保存控制台显示的信息 出现异常!" + err.Message);
}
finally
{
//如果流不为空,关闭它
}
}