0

如何在日志文件(.txt)的大小达到阈值级别(例如 5MB)时自动备份它。备份文件名应类似于 (log_file_name)_(system_date) 并且应清除原始日志文件 (0 KB)。

请帮忙。提前致谢。

4

1 回答 1

0

使用 lenght() 检查您的日志文件大小。然后检查它是否大于 5mb 调用 extendLogFile() 函数。

这是您可以轻松转换为 java 的 c# 代码

尺寸检查:

if (size > 400 * 100 * 100)
{
   extendLogFile(Path);
}

复制存档目录中的旧日志文件并创建新的日志文件:

private static void extendLogFile(string lPath)
{
        string name = lPath.Substring(0, lPath.LastIndexOf("."));
        string UniquName = GenerateUniqueNameUsingDate(); // create a unique name for old log files like '12-04-2013-12-43-00'

        string ArchivePath = System.IO.Path.GetDirectoryName(lPath) + "\\Archive";
        if (!string.IsNullOrEmpty(ArchivePath) && !System.IO.Directory.Exists(ArchivePath))
        {
            System.IO.Directory.CreateDirectory(ArchivePath);
        }

        string newName = ArcivePath + "\\" + UniquName;

        if (!File.Exists(newName))
        {

            File.Copy(lPath, newName + ".txt");

            using (FileStream stream = new FileStream(lPath, FileMode.Create))
            using (TextWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine("");
            }
        }


 }
于 2013-05-08T12:46:43.040 回答