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

前端 未结 18 1978
醉话见心
醉话见心 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条回答
  • 2020-12-02 06:45

    Here's a 1-liner lambda:

    Directory.GetFiles(dirName)
             .Select(f => new FileInfo(f))
             .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
             .ToList()
             .ForEach(f => f.Delete());
    
    0 讨论(0)
  • 2020-12-02 06:47

    The most canonical approach when wanting to delete files over a certain duration is by using the file's LastWriteTime (Last time the file was modified):

    Directory.GetFiles(dirName)
             .Select(f => new FileInfo(f))
             .Where(f => f.LastWriteTime < DateTime.Now.AddMonths(-3))
             .ToList()
             .ForEach(f => f.Delete());
    

    (The above based on Uri's answer but with LastWriteTime.)

    Whenever you hear people talking about deleting files older than a certain time frame (which is a pretty common activity), doing it based on the file's LastModifiedTime is almost always what they are looking for.

    Alternatively, for very unusual circumstances you could use the below, but use these with caution as they come with caveats.

    CreationTime
    .Where(f => f.CreationTime < DateTime.Now.AddMonths(-3))
    

    The time the file was created in the current location. However, be careful if the file was copied, it will be the time it was copied and CreationTime will be newer than the file's LastWriteTime.

    LastAccessTime
    .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
    

    If you want to delete the files based on the last time they were read you could use this but, there is no guarantee it will be updated as it can be disabled in NTFS. Check fsutil behavior query DisableLastAccess to see if it is on. Also under NTFS it may take up to an hour for the file's LastAccessTime to update after it was accessed.

    0 讨论(0)
  • 2020-12-02 06:48

    Basically you can use Directory.Getfiles(Path) to get a list of all the files. After that you loop through the list and call GetLastAccessTim() as Keith suggested.

    0 讨论(0)
  • 2020-12-02 06:52
             //Store the number of days after which you want to delete the logs.
             int Days = 30;
    
              // Storing the path of the directory where the logs are stored.
               String DirPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6) + "\\Log(s)\\";
    
              //Fetching all the folders.
                String[] objSubDirectory = Directory.GetDirectories(DirPath);
    
                //For each folder fetching all the files and matching with date given 
                foreach (String subdir in objSubDirectory)     
                {
                    //Getting the path of the folder                 
                    String strpath = Path.GetFullPath(subdir);
                    //Fetching all the files from the folder.
                    String[] strFiles = Directory.GetFiles(strpath);
                    foreach (string files in strFiles)
                    {
                        //For each file checking the creation date with the current date.
                        FileInfo objFile = new FileInfo(files);
                        if (objFile.CreationTime <= DateTime.Now.AddDays(-Days))
                        {
                            //Delete the file.
                            objFile.Delete();
                        }
                    }
    
                    //If folder contains no file then delete the folder also.
                    if (Directory.GetFiles(strpath).Length == 0)
                    {
                        DirectoryInfo objSubDir = new DirectoryInfo(subdir);
                        //Delete the folder.
                        objSubDir.Delete();
                    }
    
                }
    
    0 讨论(0)
  • 2020-12-02 06:54

    Something like this outta do it.

    using System.IO; 
    
    string[] files = Directory.GetFiles(dirName);
    
    foreach (string file in files)
    {
       FileInfo fi = new FileInfo(file);
       if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
          fi.Delete();
    }
    
    0 讨论(0)
  • 2020-12-02 06:55

    Something like that

                foreach (FileInfo file in new DirectoryInfo("SomeFolder").GetFiles().Where(p => p.CreationTime < DateTime.Now.AddDays(-90)).ToArray())
                    File.Delete(file.FullName);
    
    0 讨论(0)
提交回复
热议问题