How to zip files on folder that have specific file type as xlsx?

  • Thread starter Thread starter engahmedbarbary
  • Start date Start date
E

engahmedbarbary

Guest
I work on c# app doing compress files using zip file I face Issue I cannot control Type of file compress as xlsx,jpg ,etc ...

so I need to add extension type(File Type) for files compress inside source folder as optional parameter to determine which files will be zip

so How to add optional parameter extension type as xlsx to function Zip .

Expected Result :

suppose I have folder name source have 3 files A.xlsx,B.xlsx ,c.jpg .

and I call function Zip(source folder, destination Folder,optional xlsx)

then it will compress files A.xlsx,B.xlsx only because I pass extension xlsx

so I need to add new parameter to function zip below that have extension type as xlsx or jpg as optional

public void Zip(string source, string destination)
{
using (Ionic.Zip.ZipFile zip = new Ionic.Zip. ZipFile
{
CompressionLevel = CompressionLevel.BestCompression
})
{
var files = Directory.GetFiles(source, "*",
SearchOption.AllDirectories).
Where(f => Path.GetExtension(f).
ToLowerInvariant() != ".zip").ToArray();

foreach (var f in files)
{
zip.AddFile(f, GetCleanFolderName(source, f));
}

var destinationFilename = destination;

if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
{
destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
}

zip.Save(destinationFilename);
}
}

private string GetCleanFolderName(string source, string filepath)
{
if (string.IsNullOrWhiteSpace(filepath))
{
return string.Empty;
}

var result = filepath.Substring(source.Length);

if (result.StartsWith("\\"))
{
result = result.Substring(1);
}

result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

return result;
}

Continue reading...
 
Back
Top