C#写文件实现,自动根据时间命名,并自动删除前一天文件
/// <summary>
/// 写日志
/// </summary>
/// <param name="text">需要写入的文字</param>
private static void WriteLog(string text)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/WebLog/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DirectoryInfo folder = new DirectoryInfo(path);
foreach (FileInfo file in folder.GetFiles("*.log"))
{
DateTime dt = file.CreationTime;
if (dt < DateTime.Today)
{
try
{
File.Delete(file.FullName);
}
catch { }
}
}
path += DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff") + ".log";
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Write))
{
StreamWriter wr = new StreamWriter(fs, Encoding.UTF8);
wr.WriteLine(text);
wr.Flush();
wr.Close();
}
}