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

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

/// 
/// 写日志
/// 
/// 需要写入的文字
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();
    }
}

你可能感兴趣的:(实用,学习)