How to zip files from folder but keep it separated - c#

I have 1 folder that contains many txt files. I want to zip them but separated.
Example:
In this folder I have A.txt, B.txt, C.txt.
I want to zip all the files but separated so the result will be A.zip, B.zip, C.zip.
string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
foreach (string fileName in Directory.GetFiles(dirFile))
{
using (ZipFile zip = new ZipFile())
{
zip.UseUnicodeAsNecessary = true;
zip.AddFile(); //dont know what to put
zip.Save(); //dont know what to put
}
}
}
Any help will be appreciated.
I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.

You could do that as follows:
foreach (string fileName in Directory.GetFiles(dirFile))
{
var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
using (ZipFile zip = new ZipFile())
{
zip.AddFile(fileName); // add A.txt to the zip file
zip.Save(zipFile); // save as A.zip
}
}
This takes all the files found in the folder dirFile, and saves them under outputPath, with the same file name but replacing the extension with .zip.

Related

Unzip Files With Sub-directories To Root Folder

I need some help.
I just have this code right now. This code is working, but it's not enough.
My code;
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
foreach (FileInfo currentFile in infoFile)
{
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName))
{
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
foreach (ZipEntry currentZip in zipFile)
{ currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently); }
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
I want to extract all zip files to Application.StartupPath folder from _ZipFiles folder with all subdirectories.
Here is one example;
I have one zip folder. Name: _ZipFolder
Before the unzip process;
Application.StartupPath\_ZipFiles\startProgram.zip
Application.StartupPath\_ZipFiles\updateProgram.zip
Application.StartupPath\_ZipFiles\Pack\testDownload.zip
Application.StartupPath\_ZipFiles\Pack\Version\repo2.zip
Application.StartupPath\_ZipFiles\Pack\Version\newClass.zip
Application.StartupPath\_ZipFiles\Ack\Library\argSetup.zip
Application.StartupPath\_ZipFiles\Ack\learnMachine.zip
Application.StartupPath\_ZipFiles\Code\zipVersion4.zip
After the unzip process (I exactly want to this extract);
Application.StartupPath\startProgram.exe
Application.StartupPath\updateProgram.exe
Application.StartupPath\Pack\testDownload.exe
Application.StartupPath\Pack\Version\repo2.cs
Application.StartupPath\Pack\Version\newClass.cs
Application.StartupPath\Ack\Library\argSetup.exe
Application.StartupPath\Ack\learnMachine.pdf
Application.StartupPath\Code\zipVersion4.exe
All files needs move to Application.StartupPath from _ZipFiles folder with subdirectories.
How to make this? Please help me.
I hope you understand what I want. I'm sorry for my bad English.
Remove the zip folder name from the current file directory name when extracting
Based on current example where you have _ZipFiles folder
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
var zipFolderName = #"\_ZipFiles";
foreach (FileInfo currentFile in infoFile) {
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName)) {
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
var destination = currentFile.DirectoryName.Replace(zipFolderName, "");
foreach (ZipEntry currentZip in zipFile) {
currentZip.Extract(destination, ExtractExistingFileAction.OverwriteSilently);
}
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
If I understood you correctly, you want to extract all files to Application.StartupPath directory instead in subfolders.
Try to change:
currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently);
to
currentZip.Extract(Application.StartupPath, ExtractExistingFileAction.OverwriteSilently);
If Application.StartupPath isn't suitable, then maybe use AppDomain.CurrentDomain.BaseDirectory

Changing the extension of multiple files to jpeg using C#

I am trying to change the extension of files within a folder to jpeg. I have used the below code to update the extension and it is working fine. But when i try to open each of the files, I am getting the error in photo viewer as "Windows photo viewer can't open this picture because the file appears to be damaged, corrupted or its too large."
DirectoryInfo d = new DirectoryInfo(#"E:\New folder (2)");
FileInfo[] Files = d.GetFiles();
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
string changed = Path.ChangeExtension(file.FullName, ".jpg");
File.WriteAllText(changed, "Changed file");
}
JPEG files are not text files. You need to Read and write bytes instead. ie:
DirectoryInfo d = new DirectoryInfo(#"E:\New folder (2)");
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string changed = Path.ChangeExtension(file.FullName, "jpg");
File.Copy(file.FullName, changed);
}
Of course file themselves should be JPEG for this to work.

c# UnauthorizedAccessException when using ZipArchive but not ZipFile

I am able to zip files from a specific folder using ZipFile.CreateFromDirectory in the following test code (I only used this code to test how zipping works):
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
ZipFile.CreateFromDirectory(strStartPath, strZipPath);
However, this zips together ALL of the contents in the folder. I am trying to zip together specific items in the folder using ZipArchive in the following code:
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
using (ZipArchive archive = ZipFile.OpenRead(strStartPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (!(entry.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractToFile(Path.Combine(strZipPath, entry.FullName));
}
}
}
It is giving the error at ZipFile.OpenRead(strStartPath). Why am I able to access the exact folder in the first block of code but not the second? Or is there an easier way to search through a folder and only zip specific items?
You are utilizing the Zip libraries wrong
Effectively you are trying to open a directory as if it were a zip file, then loop over the contents of that directory (which again is actually a zip file) and then attempting to extract each member into a different zip file
Here is a working example of what you have described you are trying to do:
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
}
}
}
This will take all the root level contents of a folder and put it in the zip file. You will need to implement your own way of getting subfolders and their contents recursively, but that is beyond the scope of this question.
EDIT: Here is a working example with proper folder recursion to select all files even in subdirectories
public void ZipFolder()
{
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in RecurseDirectory(strStartPath))
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
var destination = Path.Combine(file.DirectoryName, file.Name).Substring(strStartPath.Length + 1);
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), destination);
}
}
}
}
public IEnumerable<FileInfo> RecurseDirectory(string path, List<FileInfo> currentData = null)
{
if (currentData == null)
currentData = new List<FileInfo>();
var directory = new DirectoryInfo(path);
foreach (var file in directory.GetFiles())
currentData.Add(file);
foreach (var d in directory.GetDirectories())
RecurseDirectory(d.FullName, currentData);
return currentData;
}

Trying Zip different folders in in a specified directory using ZipFile

I found the code below on stack overflow which I tried but didn't know how to use it fully.
Basically I want to be able to zip all the files separately using foreach loop but I won't have a list of the files as they change each time.
So how can I get a list of the folders/directories inside the root directory into an array?
public static void CreateZipFile(string fileName, IEnumerable<string> files)
{
var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);
foreach (var file in files)
{
zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
}
zip.Dispose();
}
Normally I just use DotNetZip
And this code:
using (var file = new ZipFile(zipName))
{
file.AddFiles(fileNames, directoryPathInArchive);
file.Save();
}
Where zipName is the name of zip archive you want to create and fileNames are names of files you want to put in it.
you need little script for this
public static class ZipUtil
{
public static void CreateFromMultifleFolders(string targetZip, string[] foldersSrc, string[] fileSrc = null, CompressionLevel compressionLevel = CompressionLevel.Fastest)
{
if (File.Exists(targetZip))
File.Delete(targetZip);
using (ZipArchive archive = ZipFile.Open(targetZip, ZipArchiveMode.Create))
{
foreach (string dir in foldersSrc)
AddFolederToZip(dir, archive, Path.GetFileName(dir), compressionLevel);
if(fileSrc != null)
foreach (string file in fileSrc)
archive.CreateEntryFromFile(file, Path.GetFileName(file), compressionLevel);
}
}
private static void AddFolederToZip(string folder, ZipArchive archive, string srcPath, CompressionLevel compressionLevel)
{
srcPath += "/";
foreach (string dir in Directory.GetDirectories(folder))
AddFolederToZip(dir, archive, srcPath + Path.GetFileName(dir), compressionLevel);
foreach (string file in Directory.GetFiles(folder))
archive.CreateEntryFromFile(file, srcPath + Path.GetFileName(file), compressionLevel);
}
}

Zipping file with DotNetZip

I am trying to zip and encrypt a chosen file from the user. Everything works fine except that I am zipping the whole path, i.e not the file itself. Below is my code, any help on how I can zip and encrypt on the chosen file.
openFileDialog1.ShowDialog();
var fileName = string.Format(openFileDialog1.FileName);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using (ZipFile zip = new ZipFile())
{
zip.Password = "test1";
zip.Encryption = EncryptionAlgorithm.WinZipAes256;
zip.AddFile(fileName);
zip.Save(path + "\\test.ZIP");
MessageBox.Show("File Zipped!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You must set the file name explicitly for the zip-archive:
zip.AddFile(fileName).FileName = System.IO.Path.GetFileName(fileName);
This is how you can zip up a file, and rename it within the archive . Upon extraction, a file will be created with the new name.
using (ZipFile zip1 = new ZipFile())
{
string newName= fileToZip + "-renamed";
zip1.AddFile(fileToZip).FileName = newName;
zip1.Save(archiveName);
}
Reference : C# Examples

Categories