【问题标题】:Delete log files programmatically以编程方式删除日志文件
【发布时间】:2015-08-25 12:06:00
【问题描述】:

我有一个保存日志文件的静态文件夹路径。我的问题是,我如何定期以编程方式删除它们,而不是手动删除。

我更喜欢 c# 代码。

【问题讨论】:

  • 我们并不是真正的代码编写服务——到目前为止您尝试了哪些方法,您的方法发现了哪些问题?查看“How do I ask a good question?”获取一些提示。

标签: c# .net windows


【解决方案1】:
File.Delete(@"some_path_to_file");

编辑:如果你想遍历目录中的所有文件,你可以使用类似的东西

DirectoryInfo dir = new DirectoryInfo("your static folder path");
foreach (FileInfo f in dir.GetFiles())
        {
            File.Delete(f.FullName);                  
        }

如果您需要“定期”执行此操作,您可以使用Quartz.NET 调度程序来调用此作业。它很容易设置。

【讨论】:

    【解决方案2】:

    根据之前的答案,这是我想出的满足我需求的方法(大型 IIS 日志文件让我发疯!):

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace LogFileDeleter
    {
        class Program
        {
            static void Main(string[] args)
            {
                DirectoryInfo dir = new DirectoryInfo("c:\\inetpub\\logs\\logfiles\\w3svc1");
                DateTime testDate = DateTime.Now.AddDays(-5);
                foreach (FileInfo f in dir.GetFiles())
                {
                    DateTime fileAge = f.LastWriteTime;
                    if (fileAge < testDate) {
                        Console.WriteLine("File " + f.Name + " is older than today, deleted...");
                        File.Delete(f.FullName);
                    }
                    //Console.ReadLine(); //Pause -- only needed in testing.
                }
            }
        }
    }
    

    应该很明显,但它只删除超过 5 天的文件,并且只删除 W3SVC1 目录中的文件。

    【讨论】:

      【解决方案3】:
      try
      {
          if(File.Exists(filePath))
          {
               File.Delete(filePath);
          }
      }
      catch{}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 2016-05-26
        相关资源
        最近更新 更多