C#写文件实现,自动根据时间命名,并自动删除前一天文件

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();
    }
}
    原文作者:风轻云断
    原文地址: https://blog.csdn.net/A156348933/article/details/79482602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞