Ionic.Zip package using C# ASP NET - c#

I try to using the Ionic.Zip library for compress the pdf files stored in public folder on my server.
This is my structure on folder C:\inetpub\wwwroot\public\
Folder
1. C:\inetpub\wwwroot\public\ALABAMA
2. C:\inetpub\wwwroot\public\FLORIDA
3. C:\inetpub\wwwroot\public\CALIFORNIA
Subfolder
- C:\inetpub\wwwroot\public\ALABAMA\April
- C:\inetpub\wwwroot\public\ALABAMA\May
- C:\inetpub\wwwroot\public\FLORIDA\April
- C:\inetpub\wwwroot\public\FLORIDA\May
- C:\inetpub\wwwroot\public\CALIFORNIA\April
- C:\inetpub\wwwroot\public\CALIFORNIA\May
For each month subfolder I have stored the corresponding PDF file.
PDF Files
- C:\inetpub\wwwroot\public\ALABAMA\April\April_ALABAMA.pdf
- C:\inetpub\wwwroot\public\ALABAMA\May\May_ALABAMA.pdf
- C:\inetpub\wwwroot\public\FLORIDA\April\April_FLORIDA.pdf
- C:\inetpub\wwwroot\public\FLORIDA\May\May_FLORIDA.pdf
- C:\inetpub\wwwroot\public\CALIFORNIA\April\April_CALIFORNIA.pdf
- C:\inetpub\wwwroot\public\CALIFORNIA\May\May_CALIFORNIA.pdf
I need compress for each folder (ALABAMA, CALIFORNIA, CALIFORNIA) the pdf files stored in subfolder May month.
I need using Ionic.Zip library get these files
1. C:\inetpub\wwwroot\public\ALABAMA\May\May_ALABAMA.pdf
2. C:\inetpub\wwwroot\public\FLORIDA\May\May_FLORIDA.pdf
3. C:\inetpub\wwwroot\public\CALIFORNIA\May\May_CALIFORNIA.pdf
and compress these files into a single zip file named May_2022.zip saving on the folder
C:\inetpub\wwwroot\public\Zip\
The code below, instead, create three different zip files
- C:\inetpub\wwwroot\public\zip\ALABAMA_may_2022_06_17_16_24.zip
- C:\inetpub\wwwroot\public\zip\FLORIDA_may_2022_06_17_16_24.zip
- C:\inetpub\wwwroot\public\zip\CALIFORNIA_may_2022_06_17_16_24.zip
And if open the zip file, I've
C:\inetpub\wwwroot\public\zip\ALABAMA\ALABAMA_may_2022_06_17_16_24.zip
C:\inetpub\wwwroot\public\zip\FLORIDA\FLORIDA_may_2022_06_17_16_24.zip
C:\inetpub\wwwroot\public\zip\CALIFORNIA\CALIFORNIA_may_2022_06_17_16_24.zip
Instead of
ALABAMA_may_2022_06_17_16_24.zip
FLORIDA_may_2022_06_17_16_24.zip
CALIFORNIA_may_2022_06_17_16_24.zip
Any suggestion?
string zipPath, filename, prevMonthIn, root, folderName;
.....
try
{
string[] states = {
"ALABAMA",
"FLORIDA",
"CALIFORNIA" };
filename = #"C:\inetpub\wwwroot\public\";
foreach (string state in states)
{
prevMonthIn = DateTime.Now.AddMonths(-1).ToString("MMMM", CultureInfo.GetCultureInfo("en-US")) + "_" +
DateTime.Now.Year;
zipPath = #"C:\inetpub\wwwroot\public\zip\" +
state.ToString() + "_" +
prevMonthIn.ToString() + "_" +
DateTime.Now.ToString("MM_dd_HH_mm") + ".zip";
root = filename.ToString() + "/" + state.ToString() + "/" + prevMonthIn.ToString();
if (Directory.Exists(root))
{
using (ZipFile zipFile = new ZipFile())
{
foreach (var item in Directory.GetDirectories(root.ToString()))
{
folderName = new DirectoryInfo(item).Name;
zipFile.AddDirectory(item, folderName);
}
foreach (string file in Directory.GetFiles(root.ToString()))
{
zipFile.AddFile(file);
}
zipFile.Save(zipPath);
}
}
}
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
}

Related

Extract zip file and overwrite (in the same directory - C#)

I'm starting some C# stuff, and i would like to extract and force to overwrite all files from a zip archive. I know that there are many other solution in Stack, but nothing works for me :/
i've tried this method:
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, extractPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
This extractor works fine, but doesn't allow me to overwrite files meanwhile extraction, and it returns error and exceptions ... i've tried to take a look at MS-Documention, without success ...
someone know how does it work ?
Try something like this. Away from my dev box so this may require some tweaking, just writing it from memory.
Edit: As someone mentioned you can use ExtractToFile which has an overwrite option. ExtractToDirectory does not.
Essentially you unzip to a temporary folder then check if an unzipped file's name already exists in the destination folder. If so, it deletes the existing file and moves the newly unzipped one to the destination folder.
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory.
Directory.Delete(tempPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
Edit, in the event directories are unzipped (again, may need to be tweaked, I didn't test it):
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped directories:
string[] folders = Directory.GetDirectories(tempPath);
foreach (string folder in folders)
{
DirectoryInfo d = new DirectoryInfo(folder);
//If the directory doesn't already exist in the destination folder, move it to the destination.
if (!Directory.Exists(Path.Combine(extractPath,d.Name)))
{
Directory.Move(d.FullName, Path.Combine(extractPath, d.Name));
continue;
}
//If directory does exist, iterate through the files updating duplicates.
else
{
string[] subFiles = Directory.GetFiles(d.FullName);
foreach (string subFile in subFiles)
{
FileInfo f = new FileInfo(subFile);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath, d.Name, f.Name)))
{
File.Delete(Path.Combine(extractPath, d.Name, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
}
}
}
//build an array of the unzipped files in the parent directory
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
Directory.Delete(tempPath);
return (0); // 0 all fine
}

Find matching files in a folder (minus file extension) and move them to a new folder

I have a directory of files that contain both Word and PDF files. Some of the Word files in the directory have the same filename (minus extension) as the PDF files in the same directory. I have setup a simple C# winforms application to loop through the files and move the Word documents that have same name as PDF documents. Here's what I have so far. I'm not sure why this isn't working:
string[] filesWORD = Directory.GetFiles(#"c:\test\", "*.docx");
List<string> resultFiles = new List<string>();
foreach (var file in filesWORD)
{
var finalfile = file.Substring(0, file.LastIndexOf(".")); // removes everything after period in name.
resultFiles.Add(finalfile);
listBox1.DataSource = resultFiles.Distinct().ToList(); // placing the Word files in listBox1
}
string[] filesPDF = Directory.GetFiles(#"c:\test\", "*.pdf");
List<string> resultFilesPDF = new List<string>();
foreach (var file in filesPDF)
{
var finalfile = file.Substring(0, file.LastIndexOf("."));
resultFilesPDF.Add(finalfile);
listBox2.DataSource = resultFilesPDF.Distinct().ToList(); // placing the PDF files in listBox2
}
for (int i = 0; i < listBox1.Items.Count; i++)
{
//IF the WORD files in listBox1 match the PDF files in listBox2 -- move them to a new folder.
foreach (string files in listBox1.Items)
{
if (listBox1.Items == listBox2.Items)
{
//Get Filename
var filename = Path.GetFileName(files + ".docx");
//Move Files
File.Move(files + ".docx", #"c:\test2\" + "\\" + filename);
}
}
}
The final for loop is where the problem is, you can try this (need to add listbox for your case), you are comparing the wrong thing, also the outer for loop is not required.
foreach (var pdfFile in resultFilesPDF)
{
foreach (var wordFile in resultFiles)
{
if (wordFile == pdfFile)
{
//Get Filename
var filename = System.IO.Path.GetFileName(wordFile + ".docx");
//Move Files
File.Move(wordFile + ".docx", #"c:\test2\" + "\\" + filename);
}
}
}
Using Linq you can do it like, be aware that if you try to move the same file multiple times the Move method might blow up.
var sameNames = resultFiles.SelectMany(w => resultFilesPDF.Where(p => p == w));
sameNames.ToList().ForEach(file =>
{
File.Move(file + ".docx", #"c:\test2\" + "\\" + System.IO.Path.GetFileName(file + ".docx"));
});

Check Zip File content and extract

Hi I want to extract a ZipFile that has various of text files. But i could be that de text files are in a folder. So what i want to do is: If an folder exists just exract normaly if not create a folder with name of ZipFile. The reason is i don't want to have a folder in a folder with the same name.
My Previous Code:
foreach (string file in newZips) {
FileInfo fileInfo = new FileInfo(file);
string dirName = newPath + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
Console.WriteLine(dirName);
Directory.CreateDirectory(dirName);
ZipFile.ExtractToDirectory(allZipsPath + "\\" + fileInfo.Name, dirName);
}
Maybe this helps you:
string path = #"C:\..\..\myFolder";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Thats how you can check a path if it contains the Folder you expect. And if not it creates that Folder!
--- EDIT (if unknown zip-Name) ---
string myPathToZip = #"C:\..\..\folderName";
foreach (string file in Directory.GetFiles(myPathToZip, "*.zip", SearchOption.AllDirectories))
{
//the current path of the zipFile (with the Name included)
var path = new FileInfo(file.ToString());
//The filename
var filename = Path.GetFileName(file.ToString()).Replace(".zip", "");
}

how to get FileName, FilePath to Store it in a Variabl and then upload that file in asp.net

I want to merge two files and save it is as new file.
e.g
a1,a2 new a3
...and then upload that file which i have merge which is a3.
I mean I am saving a file in a folder , i want when i save , i get exactly that f filename as well filepath.
here is my code.
protected void Button1_Click(object sender, EventArgs e)
{
string fname = "";
if (txtFile.HasFile)
{
try
{
HttpFileCollection uploadedFiles = Request.Files;
// Get the HttpFileCollection
string[] filespath = new string[15];
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile hpfiles = uploadedFiles[i];
fname = Path.GetFileName(hpfiles.FileName);
if (hpfiles.ContentLength > 0)
{
hpfiles.SaveAs(Server.MapPath("~/Images/") + Path.GetFileName(hpfiles.FileName));
hpfiles.SaveAs(Server.MapPath(Path.Combine(#"~/Images/", fname)));
string filepath = Server.MapPath(#"~/Images/");
string path = filepath + fname;
filespath[i] = path;
}
}
// MergeFiles(#"C:\ENROLLDOCS\New Document.pdf"+DateTime.Now.ToFileTime(), filespath);
MergeFiles(#"D:\Razim\MedFlow\tempp\New Document.pdf" + " " + DateTime.Now.ToFileTime() + ".pdf", filespath);
// now i want to get the filename and filepath which i have merged and saved, for uploading.
}
catch (Exception ex)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
iTextSharp is a C# PDF library that can read and write PDF's based on the iText library, it's free for open source... paid for commercial use. Here is an existing example of how to merge two PDF's using their library, you can easily adapt it to the file upload scenario.
Merging multiple PDFs using iTextSharp in c#.net

C# File.Move won't find existing file?

I have a method that unzips files into an 'unzipped' files folder. Problem is that there are files duplicated in two zip files - so when the second zip file is extracted the process fails as the file name already exists. I decided to rename the existing file to avoid this problem, but my if(File.Exists...) statement is not picking up files that exist. This is probably a noob syntax issue?
private void UnzipFiles()
{
sourceDirectory = #"c:\id";
unzippedDirectory = #"C:\id\z_unzipped";
processedDirectory = #"C:\id\z_processed";
// get list of files from directory and unzip them
DirectoryInfo dirInfo = new DirectoryInfo(sourceDirectory);
FileInfo[] infos = dirInfo.GetFiles("*.zip");
foreach (FileInfo f in infos)
{
if (File.Exists(unzippedDirectory + #"\" + f.Name)){
// rename existing file
File.Move(unzippedDirectory + #"\" + f.Name, unzippedDirectory + #"\" + f.Name + " renamed by " + f.Name);
}
System.IO.Compression.ZipFile.ExtractToDirectory(f.FullName, unzippedDirectory);
File.Move(f.FullName, processedDirectory + #"\" + f.Name);
}
}

Categories

Resources