I have a list of logfiles which have their creation-date in their filename. I'm trying to zip the files together by date. Obviously I'm doing something wrong. How can I achieve this? This program is going to be a scheduled executable that zip log files every day, hence the currentDate variable. It could be 1 or several logfiles so the program should not depend on a number of files to zip.
These are the names of the log files:
Log_2021-06-17_1.txt,
Log_2021-06-17_2.txt,
Log_2021-06-17_3.txt
string currentDate = DateTime.Today.ToString("yyyy-MM-dd");
var logDir = new DirectoryInfo(@"C:\Users\user\Desktop\LogFilesTEST\In\");
foreach (FileInfo logFile in logDir.GetFiles())
{
if (logFile.Name.Contains(currentDate))
{
string startPath = @"C:\Users\user\Desktop\LogFilesTEST\In\" + logFile.Name;
string zipPath = @"C:\Users\user\Desktop\LogFilesTEST\Archive\" + logFile.Name + ".zip";
ZipFile.CreateFromDirectory(startPath, zipPath);
}
}
Edit: if someone has the same problem here is what i did in my Console application:
Program Class
class Program
{
static void Main(string[] args)
{
string currentDate = DateTime.Today.ToString("yyyy-MM-dd");
var logDir = new DirectoryInfo(@"C:\Users\user\Desktop\LogFilesTEST\In\");
List<FileInfo> LogFileList = new List<FileInfo>();
foreach (FileInfo logFile in logDir.GetFiles())
{
if (logFile.Name.Contains(currentDate))
{
LogFileList.Add(logFile);
}
}
Zipper.CreateZipFile(LogFileList, @"C:\Users\user\Desktop\LogFilesTEST\Archive\Logs_" + currentDate + ".zip");
foreach(var logfile in LogFileList)
{
logfile.Delete();
}
}
}
Zipper Class:
class Zipper
{
public static void CreateZipFile(List<FileInfo> files, string archiveName)
{
using (var stream = File.OpenWrite(archiveName))
using (ZipArchive archive = new ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create))
{
foreach (var item in files)
{
archive.CreateEntryFromFile(item.FullName, item.Name, CompressionLevel.Optimal);
}
}
}
}