Home > Back-end >  Filter txt files by the creation date
Filter txt files by the creation date

Time:06-16

I'm doing a tool that is supposed to zip some ".txt" files by the dates of creation.

What I want is to compress in Zip all the txt files created in the same day from a specific folder. I can't find a way to filter the files by the dates.

CodePudding user response:

The File library has a method GetCreationTime which takes the path as a string.

Using this method, you could filter your files.

CodePudding user response:

quick and dirty:

using System.Linq;
using System.IO;
using System.IO.Compression;

public static void GetTxtFiles()
        {
            var directoryInfo = new DirectoryInfo("pathToFolder");
            var specificDay = new DateTime(2022, 06, 15).Date;

            var txtFiles = directoryInfo.GetFiles("*.txt")
                .Where(x => x.CreationTime.Date.Equals(specificDay))
                .ToList();
            if (txtFiles.Count == 0)
                throw new FileNotFoundException("No txt files have been found");
            ArchiveFiles("pathToZip", txtFiles);
        }

        private static string ArchiveFiles(string zipCreatePath, List<FileInfo> filesToZip)
        {
            if (File.Exists(zipCreatePath))
                File.Delete(zipCreatePath);

            using (ZipArchive archive = ZipFile.Open(zipCreatePath, ZipArchiveMode.Create))
            {
                foreach (var file in filesToZip)
                {
                    archive.CreateEntryFromFile(file.FullName, file.Name);
                }
            }
            return zipCreatePath;
        }
  • Related