Auto Extract a zip file - c#

I'm trying make a program that extracts a specific zip file everytime the program launches.
this is my code to create the zip file:
//creating the file
ZipFile File = new ZipFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip");
//Adding files
File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ab.dat", "");
File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\cd.dat", "");
//Save the file
File.Save();
I want to Extract the files ab.dat and cd.dat from ABCD.zip to the .exe file directory automatically.
Thanks for helping.

Taken mostly from the DotNetZip documentation:
private void Extract()
{
//Zip Location
string zipToUnpack = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip";
// .EXE Directory
string unpackDirectory = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
using (ZipFile zip = ZipFile.Read(zipToUnpack))
{
foreach (ZipEntry e in zip)
{
//If filename matches
if (e.FileName == "ab.dat" || e.FileName == "cd.dat")
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
}
You can also filter the results using ExtractSelectEntries by selecting the files there:
zip.ExtractSelectedEntries("name = 'ab.dat' OR name = 'cd.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Or selecting all .dat files with a wildcard
zip.ExtractSelectedEntries("name = '*.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Use each ZipEntry's FileName property to see if it has the name you would like to extract.

Related

C# Unable to unzip files zipped with CreateEntryFromFile

As per this post I'm zipping SQL backup files with the code below:
using (ZipArchive zip = ZipFile.Open("test.bak", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#"c:\something.txt", "data/path/something.txt");
}
The zip file are created successfully with the correct file size. But I can't unzip the file. I get the the error:
The compressed (zip) folder is invalid or corrupted
I've tried using 7-zip and the build-in Windows 'Extract All' options.
I also tried reinstalling the software with no luck.
My version of the code:
var fileName = Path.GetFileName(e.FullPath);
var newFile = dir + "\\" + fileName + ".zip";
var backupFile = txtBackupFolder.Text == "" ? "" : txtBackupFolder.Text + "\\" + fileName + ".zip";
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#e.FullPath, newFile);
}
Nkosi's post above did help, but I think what added to the problem was the escape characters in the newfile variable.
This does work:
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#e.FullPath, "mybackup.bak");
}
I faced this very issue, and mine was related to special characters in the file names I was generating (specifically, a : character). So my code looked like
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
var title = GetTitleOfHtmlFile(); //code to get the file name to use
zip.CreateEntryFromFile(#e.FullPath, title); // title = "Chapter 1: My Chapter.html"
}
As the title being generated contained path-unfriendly characters, while I could add the entry to a zip file, when I tried to unzip the file, the OS would freak out because it couldn't deal with the path-unfriendly characters in the entry's name.
I simply changed the title to include an extension method to strip out such things, as so
title.ReplaceScreenUnfriendlyChars("-");
With an extension method like this:
public static string ReplaceScreenUnfriendlyChars(
this string curString,
string replacementString = "")
{
return string.Join(replacementString, curString.Split(Path.GetInvalidFileNameChars()));
}

rename file by adding an incrementing number to old file name c#

I'm writing my first Cocoa app in c#, its suppose to append/add numbers at the begging of a file name.
Users give only the path to the folder (for example with music), and for each file included in folder the program suppose to add incrementing numbers like
001_(old_fileName),
002_(old_fileName),
...,
092_(old_fileName)
etc,
Untill the end of files in given folder (by path).
There is no way to split a file name, cause file names are not known (may even include numbers itself). I've tried few possible options to solve this, but non of them works. Found few already asked question with changing names in c# but non of the results actually helped me.
The code under is the rest I've got at the moment, all non-working tries were firstly commented and later deleted. by NSAlert i see the path/name of each file in folder as a help. I would be more than happy to receive help
void RenameFunction()
{
string sPath = _Path_textBox.StringValue;
if (Directory.Exists(sPath))
{
var txtFiles = Directory.EnumerateFiles(sPath);
var txt2Files = Directory.GetFiles((sPath));
string fileNameOnly = Path.GetFileNameWithoutExtension(sPath);
string extension = Path.GetExtension(sPath);
string path = Path.GetDirectoryName(sPath);
string newFullPath = sPath;
int count = 1;
while (File.Exists(sPath))//newFullPath))
{
string tempFileName = string.Format(count + "_" + fileNameOnly + sPath);
//count++;
//string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
newFullPath = Path.Combine(path, extension + tempFileName);
count++;
}
string[] fileEntities = Directory.GetFiles(newFullPath); //GetFileSystemEntries(sPath);//GetFiles(sPath);
//foreach (var _songName in fileEntities)
//{
// string tempFileName = count + "_" + fileNameOnly + sPath;
// //string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
// newFullPath = Path.Combine(sPath ,extension + tempFileName);
// File.Move(sPath, newFullPath);
//}
foreach (var _songName in fileEntities)
{
AmountofFiles(_songName);
}
}
}
void AmountofFiles(string path)
{
var alert2 = new NSAlert();
alert2.MessageText = "mp3";
alert2.InformativeText = "AMOUNT OF MP3 FILES IS '{1}' : " + path;
alert2.RunModal();
}
Have you try use File.Move? Just move file to same path, but another name
File.Move("NameToBeRename.jpg","NewName.jpg");
There are multiple things which are not right with the code you share. The thing which want to achieve can be implemented using very simple approach.
All you need to do is retrieve all the files names with the full path from the directory and rename them one by one.
Follow the below code which demonstrates the above mentioned approach.
// Path of the directory.
var directroy = _Path_textBox.StringValue;
if (Directory.Exists(directroy))
{
//Get all the filenames with full path from the directory.
var filePaths = Directory.EnumerateFiles(directroy);
//Variable to append number in front of the file name.
var count = 1;
//Iterate thru all the file names
foreach (var filePath in filePaths)
{
//Get only file name from the full file path.
var fileName = Path.GetFileName(filePath);
//Create new path with the directory path and new file name.
var destLocation = Path.Combine(directory, count + fileName);
//User File.Move to move file to the same directory with new name.
File.Move(filePath, destLocation);
//Increment count.
count++;
}
}
I hope this helps you to resolve your issue.

Ionic Zip cannot zip folder inside folder C#

I am trying to zip a folder using IonicZip library in C#. It is able to zip .txt, .exe, .pdf etc. in the folder, but not able to zip folder in folder.
It is able to zip MusicLogs.txt and Video.exe but cannot Music folder.Music folder contains some folder also. It doesnt see Music folder even while debugging. My code is :
string zipPath = #"C:\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm") + ".zip"; // zipped file extracts here
string filename = #"E:\"; // the fodler which should be zipped. File must be exist
using (ZipFile zipFile = new ZipFile())
{
zipFile.Password = "asd";
zipFile.Encryption = EncryptionAlgorithm.PkzipWeak;
foreach (string file in Directory.GetFiles(filename)) // this foreach is for getting all files in a folder.
{
zipFile.AddFile(file, "YESMusic"); // set file
}
zipFile.Save(zipPath);
}
Where is the problem ? Need a change in AddFile function ? Thanks
This will work:
using (ZipFile zipFile = new ZipFile())
{
zipFile.Password = "asd";
zipFile.Encryption = EncryptionAlgorithm.PkzipWeak;
// Adding folders in the base directory
foreach (var item in Directory.GetDirectories(filename))
{
string folderName = new DirectoryInfo(item).Name;
zipFile.AddDirectory(item, folderName);
}
// Adding files in the base directory
foreach (string file in Directory.GetFiles(filename))
{
zipFile.AddFile(file);
}
zipFile.Save(zipPath);
}

How to recursively copy file an folder in .Net?

I have the following script, which take a source folder and copy using FileStream files to another folder.
I need to change it in a way to recursively get any sub-folders and copy their files too.
How to modifythe method?
- source folder
- file
- file
- folder
- file
- file
- folder
- file
- folder
- file
- file
- folder
- file
public static void SynchFolders()
{
DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);
foreach (FileInfo file in StartDirectory.EnumerateFiles())
{
using (FileStream SourceStream = file.OpenRead())
{
string dirPath = StartDirectory.FullName;
string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
Basically what you need to do is to expand your function slightly such that after copying all files found in a particular directory, it will then search for subfolders within the current folder and recurse into that folder so that the same procedure is carried out on each subfolder.
An example function, based on your original code :
public static void SynchFolders(string SourceUNC, string TargetUNC)
{
DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);
// Copy Files
foreach (FileInfo file in StartDirectory.EnumerateFiles())
{
using (FileStream SourceStream = file.OpenRead())
{
string dirPath = StartDirectory.FullName;
string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
// Copy subfolders
var folders = StartDirectory.EnumerateDirectories();
foreach (var folder in folders)
{
// Create subfolder target path by concatenating folder name to original target UNC
string target = Path.Combine(TargetUNC, folder.Name);
Directory.CreateDirectory(target);
// Recurse into the subfolder
SynchFolders(folder.FullName, target);
}
}
Hope this helps
How to: Copy Directories is an article from MSDN showing how to do exactly what you need.
Read this MSDN Tutorial (exacly what you need): http://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
Note: if you'd like to use SourceStream.CopyToAsync instead of file.CopyTo, just replace it with your original snippet

Search for filename on Server

Im creating a website where it is possible to uploade an excel file end extract data from it. In my code i uploade the excel file to the application on the server in an Uploade folder and extract data from it.
I am renaming the filename to a string with date and time so i delete files that is not matching the string i get from DateTime.Now since i dont wanna fill my server with excel files.
So i want to check for existing files in the Uploade folder on my server, and if there is older excel files i want to delete them.
How do i get the folder content from my server ?
My code:
protected void uploadButton_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile)
{
string fileuploaded = Server.MapPath("Upload") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "excel" + Path.GetExtension(fileUpload.FileName);
fileUpload.SaveAs(fileuploaded);
}
}
You can use the Directory.GetFiles method for this:
string folder = Server.MapPath("Upload");
foreach (var filePath in Directory.GetFiles(folder, "*excel*"), SearchOption.TopDirectoryOnly)
{
FileInfo fi = new FileInfo(filePath);
if ((DateTime.Now - fi.CreationTime).TotalDays > 30)
{
File.Delete(filePath);
}
}
You also can parse the creation date from the filename using DateTime.ParseExact().
string folder = Server.MapPath("Upload");
foreach (var item in Directory.GetFiles(folder))
{
FileInfo fi = new FileInfo(item);
DateTime creationDate = fi.CreationTime;
//TODO: check creation date and delete files you want...
}

Categories

Resources