2

I have lots of logs in a folder, I would like to only grab files that have todays date and put them in the zip file.

Here is my code:

static void Main(string[] args)
{
    //Specify todays date
    DateTime todaysDate = DateTime.Today;

    //Create a zip file with the name logs + todays date
    string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
    string myPath = @"C:\Users\Desktop\LOG SEARCH";

    var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

    foreach (var file in files)
    {
        Console.WriteLine(file);
    }
}

How do I zip files ?

Tony
  • 474
  • 1
  • 7
  • 19

2 Answers2

3

So what you can do is create a temporary folder and then add each file that matches the current date in it. Once that's done you can ZipFile.CreateFromDirectory and then delete the temporary folder

DateTime todaysDate = DateTime.Today;

//Create a zip file with the name logs + todays date
string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
string myPath = @"C:\Users\Desktop\LOG SEARCH";

string tempPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd");

var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

Directory.CreateDirectory(tempPath);

foreach (var file in files)
{
    File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));
}

ZipFile.CreateFromDirectory(tempPath, zipPath);

Directory.Delete(tempPath, true);
I.B
  • 2,925
  • 1
  • 9
  • 22
0

You need to use System.IO.Compression; and use

 ZipFile.CreateFromDirectory(myPath, zipPath);
Urvil Shah
  • 73
  • 9
  • this will grab all the files in the directory, I only want specific ones – Tony Jul 06 '17 at 18:20
  • Probably you looking for :https://stackoverflow.com/questions/27550413/how-to-zip-selected-files-not-all-the-files-in-a-directory-in-c-sharp – Urvil Shah Jul 06 '17 at 18:23
  • this is a different solution. I need to recreated my whole program – Tony Jul 06 '17 at 18:24