Home » c# » c# – use loop to check the files in directory and add the files that have the same date on the filename to a zip folder-Exceptionshub

c# – use loop to check the files in directory and add the files that have the same date on the filename to a zip folder-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I need to check the files in the directory which all the files have the format like filename_20200219 and zip all the files which have the same date based on the date from the filename. How can this be done?

For example, a_20200219, b_20200219, c_20200220, d_20200220

The output after zipping should be:

a_20200219 and b_20200219 in a zip folder

c_20200220 and d_20200220 in another zip folder.

Thanks in advance.

How to&Answers:

Use Directory.EnumerateFiles(path) to retrieve all the files in a directory.
Than Path.GetFileNameWithoutExtension(filePath) to get its name.
Than split it on the ‘_’ with var elements = fileName.Split('_');.
At position 1 there will be the date var date = elements[1];.
So now you can group files having the same date.

To be able to create a zip file you need to create a new directory and copy there your files having the same date.

I hope I was helpful