Delete files older than 3 months old in a directory using .NET

前端 未结 18 2059
醉话见心
醉话见心 2020-12-02 06:31

I would like to know (using C#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible.

Just to be clear:

18条回答
  •  -上瘾入骨i
    2020-12-02 06:55

    i have try this code and it works very well, hope this answered

    namespace EraseJunkFiles
    {
        class Program
        {
            static void Main(string[] args)
            {
                DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\yourdirectory\");
                foreach (FileInfo file in yourRootDir.GetFiles())
                    if (file.LastWriteTime < DateTime.Now.AddDays(-90))
                        file.Delete();
            }
        }
    }
    

提交回复
热议问题