Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How to zip files(Any files or folder ) in vb.net 2005?
DotNetZip is an easy-to-use, free, open-source library for handling ZIP files in VB.NET and other .NET languages.
Some sample VB.NET code, to create a zip file, adding files one at a time:
Dim ZipToCreate As String = "ex1.zip"
Dim DirectoryToZip As String = "c:\temp"
Using zip As ZipFile = New ZipFile
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
Dim filename As String
For Each filename In filenames
zip.AddFile(filename)
Next
zip.Save(ZipToCreate)
End Using
Or, add files in a group:
Dim ZipToCreate As String = "ex1.zip"
Dim DirectoryToZip As String = "c:\temp"
Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
Using zip As ZipFile = New ZipFile
zip.AddFiles(filenames, "temp")
zip.Save(ZipToCreate)
End Using
or, Code to zip up an entire directory or folder:
Using zip As ZipFile = New ZipFile
zip.AddDirectory(directory)
zip.Save(targetZip)
End Using
Code to extract a zip file:
Dim ZipFileToExtract As String = "c:\foo.zip"
Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
Dim e As ZipEntry
For Each e In zip
' can conditionally extract here, '
' based on name, size, date, whatever.'
e.Extract
Next
End Using
Extract with a progress bar:
Imports Ionic.Zip
Module SimpleUnzip
Public Sub Unzip(ByVal ZipToUnpack As String, ByVal ExtractDirectory As String)
Try
Using zip As ZipFile = ZipFile.Read(ZipToUnpack)
Form1.ProgressBar1.Maximum = zip.Entries.Count
Dim entry As ZipEntry
For Each entry In zip
Form1.Label1.Text = entry.FileName
entry.Extract(ExtractDirectory, ExtractExistingFileAction.OverwriteSilently)
Form1.ProgressBar1.Value = Form1.ProgressBar1.Value + 1
' sleep because it's too fast otherwise.
System.Threading.Thread.Sleep(50)
Next
Form1.ProgressBar1.Value = 0
Form1.Label1.Text = "Done"
End Using
Catch ex1 As Exception
Form1.Label1.Text = ("Exception: " & ex1.ToString())
End Try
End Sub
End Module
DotNetZip has progress events for reading, saving, or extracting, so you can power progress bars in ASP.NET or Windows Forms. It does password-protected zip files, Unicode, ZIP64, and self-extracting archives. The zip files it produces are compatible with all other zip tools - WinZip, WinRAR, Windows Explorer, Pkunzip, etc. There's a good help file (online version here) with tons of code examples. There are samples available for download, too.
Have a look at SharpZipLib
I do not know how to program in VB.NET. However, a search revealed an interesting link: Zip Compression VB.NET Examples. I hope it will be useful to you.
You can use ICSharCode's SharpZipLib library.
You can use our Rebex ZIP component.
Here are some samples of operations you are asking for:
Simple zipping files in one line of code:
' add content of the local directory C:\Data\ '
' to the directory \Data-2010 (within the ZIP archive) '
' (ZIP archive C:\archive.zip doesn't have to exist)
ZipArchive.Add("C:\archive.zip", "C:\Data\*", "\Data-2010")
Simple unzipping in one line of code:
' extract all *.TXT files from the directory \Data-2010 (within the ZIP file) '
' to the existing local directory C:\Data '
ZipArchive.Extract("C:\archive.zip", "\Data-2010\*.html", "C:\Data")
More samples can be found here.
Shell it, wa-la done in two lines
Dim zipcmd as String = "zip -r C:\directory\of\my\folder C:\directory\of\my\zip"
Shell("cmd.exe /c" + zipcmd1, AppWinStyle.Hide, True)
Related
I am trying to save a image from webbrowser but can't find an answer for it.
Example of the problem is the URL is hxxp://domain[.]com/image/?img=1234 on webbrowser it shows the image and the source is <img src='hxxp://domain[.]com/image/?img=1234'>..
I was unable to save it using the My.Computer.Network.DownloadFile and MemoryStream(tClient.DownloadData methods.
In order to download the file, I will need to session cookie also?
How can I do this?
Any image that you see in the WebBrowser has already been downloaded to your computer. It is normally cached in the folder:
C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files
or whatever other folder is set in Internet Options. You can get your image from that folder.
The following program shows how to copy file TDAssurance_Col.png from the Temporary Internet Files folder to the C:\Temp folder.
Module Module1
Sub Main()
CopyFileFromTemporaryInternetFolder("TDAssurance_Col.png", "C:\Temp")
End Sub
Public Sub CopyFileFromTemporaryInternetFolder(filename As String, destinationFolder As String)
' Search actual path of filename.
Dim temporaryInternetFilesFolder As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), "Content.IE5")
Dim pattern As String = Path.GetFileNameWithoutExtension(filename) & "*" & Path.GetExtension(filename)
Dim pathnames() As String = Directory.GetFiles(temporaryInternetFilesFolder, pattern, SearchOption.AllDirectories)
' If file found, copy it.
If pathnames.Count > 0 Then
File.Copy(pathnames(0), Path.Combine(destinationFolder, filename))
End If
End Sub
End Module
I am using the free licenced version of Spire PDF. My program has in the region of 166,ooo pdf files which represent individual pages. I need to merge between 1 and 20 of these with the same names into one pdf.
I have a routine the builds a string of filenames to be added to an array which is passed to the following sub as PDFFiles. The OutputFile is the string with the name of the output file with it's path.
Private Sub MergePDFs(ByVal PDFFiles As String, ByVal OutPutFile As String)
Dim files As [String]() = New [String]() {"E:\Ballads of the 20th Century\1st bari #1.pdf", "E:\Ballads of the 20th Century\1st bari #2.pdf"}
Dim i As Integer
'open pdf documents
Dim docs As PdfDocument() = New PdfDocument(files.Length - 1) {}
For i = 0 To files.Length - 1
docs(i) = New PdfDocument(files(i))
Next
'append document
docs(0).AppendPage(docs(1))
'import PDF pages
i = 0
While i < docs(2).Pages.Count
docs(0).InsertPage(docs(2), i)
i = i + 2
End While
End Sub
I have the Solution Explorer I have the Spire.Pdf.dll as a file. In References I have Spire.Pdf and Spire.Licence.
At runtime I get An unhandled exception of type 'System.ArgumentException' occurred in Spire.Pdf.dll
Additional information: File doesn't exist.
The PDFFiles is not used in this example for clarity. The two files listed are taken directly from the program output for testing purposes.
There has to be a simple explanation for this error, but I haven't found one yet.
Please can you help solve it.
Thanks
Graham
I found the answer to this myself.
The actual problem was the way Spire.pdf parses a string into a pdf document.
There must be no spaces in the filename, then it works fine.
Graham
I have a .zip folder in the .exe resources and I have to move it out and then extract it to a folder. Currently I am moving the .zip out with System.IO.File.WriteAllByte and unziping it. Is there anyway to unzip straight from the resources to a folder?
Me.Cursor = Cursors.WaitCursor
'Makes the program look like it's loading.
Dim FileName As FileInfo
Dim Dir_ExtractPath As String = Me.tb_Location.Text
'This is where the FTB folders are located on the drive.
If Not System.IO.Directory.Exists("C:\Temp") Then
System.IO.Directory.CreateDirectory("C:\Temp")
End If
'Make sure there is a temp folder.
Dim Dir_Temp As String = "C:\Temp\Unleashed.zip"
'This is where the .zip file is moved to.
Dim Dir_FTBTemp As String = Dir_ExtractPath & "\updatetemp"
'This is where the .zip is extracted to.
System.IO.File.WriteAllBytes(Dir_Temp, My.Resources.Unleashed)
'This moves the .zip file from the resorces to the Temp file.
Dim UnleashedZip As ZipEntry
Using Zip As ZipFile = ZipFile.Read(Dir_Temp)
For Each UnleashedZip In Zip
UnleashedZip.Extract(Dir_FTBTemp, ExtractExistingFileAction.DoNotOverwrite)
Next
End Using
'Extracts the .zip to the temp folder.
So if you're using the Ionic library already, you could pull out your zip file resource as a stream, and plug that stream into Ionic to decompress it. Given a resource of My.Resources.Unleashed, you have two options for getting your zip file into a stream. You can load up a new MemoryStream from the bytes of the resource:
Using zipFileStream As MemoryStream = New MemoryStream(My.Resources.Unleashed)
...
End Using
Or you can use the string representation of the name of the resource to pull a stream directly from the assembly:
Dim a As Assembly = Assembly.GetExecutingAssembly()
Using zipFileStream As Stream = a.GetManifestResourceStream("My.Resources.Unleashed")
...
End Using
Assuming you want to extract all the files to the current working directory once you have your stream then you'd do something like this:
Using zip As ZipFile = ZipFile.Read(zipFileStream)
ForEach entry As ZipEntry In zip
entry.Extract();
Next
End Using
Taking pieces from here and there, this works with 3.5 Framework on Windows 7:
Dim shObj As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
Dim tmpZip As String = My.Application.Info.DirectoryPath & "\tmpzip.zip"
Using zip As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("myProject.myfile.zip")
Dim by(zip.Length) As Byte
zip.Read(by, 0, zip.Length)
My.Computer.FileSystem.WriteAllBytes(tmpZip, by, False)
End Using
'Declare the output folder
Dim output As Object = shObj.NameSpace(("C:\destination"))
'Declare the input zip file saved above
Dim input As Object = shObj.NameSpace((tmpZip)) 'I don't know why it needs to have double parentheses, but it fails without them
output.CopyHere((input.Items), 4)
IO.File.Delete(tmpZip)
shObj = Nothing
Sources: answers here and https://www.codeproject.com/Tips/257193/Easily-Zip-Unzip-Files-using-Windows-Shell
Since we are using the shell to copy the files, it will ask the user to overwrite them if already exist.
I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box
I am a programmer using VS2012. I am wanting to unzip a zip file (made with Winzip, filzip or other zip compression routines) and then also be able to zip the files back up into a zip file.
What is the best library to use for this and can I please have some sample code on how to use the library?
EDIT
I am using VB.net, here is my code:
Public Function extractZipArchive() As Boolean
Dim zipPath As String = "c:\example\start.zip"
Dim extractPath As String = "c:\example\extract"
Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
For Each entry As ZipArchiveEntry In archive.Entries
If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName))
End If
Next
End Using
End Function
What import statements do I need to use?
Currently I have added the following:
Imports System.IO
Imports System.IO.Compression
I am getting the error:
Type 'ZipArchive' is not defined
How can I fix this error?
If you're using Visual Studio 2012 and the .NET Framework 4.5 you can use the new compression library:
//This stores the path where the file should be unzipped to,
//including any subfolders that the file was originally in.
string fileUnzipFullPath;
//This is the full name of the destination file including
//the path
string fileUnzipFullName;
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(zipName))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
//Outputs relevant file information to the console
Console.WriteLine("File Name: {0}", file.Name);
Console.WriteLine("File Size: {0} bytes", file.Length);
Console.WriteLine("Compression Ratio: {0}", ((double)file.CompressedLength / file.Length).ToString("0.0%"));
//Identifies the destination file name and path
fileUnzipFullName = Path.Combine(dirToUnzipTo, file.FullName);
//Extracts the files to the output folder in a safer manner
if (!System.IO.File.Exists(fileUnzipFullName))
{
//Calculates what the new full path for the unzipped file should be
fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);
//Creates the directory (if it doesn't exist) for the new path
Directory.CreateDirectory(fileUnzipFullPath);
//Extracts the file to (potentially new) path
file.ExtractToFile(fileUnzipFullName);
}
}
}
Unanswered, although a while ago, so I'll still put my $0.02 in there for anyone else who hits this on keywords...
VB 2012 (.Net 4.5) added new features to System.IO.Compression (System.IO.Compression.FileSystem.dll) that will do what you want. We only had GZip before. You can still use the free DotNetZip or SharpZipLib, of course.
The ZipFile class has 2 static methods that make simple compression/decompression drop-dead simple: CreateFromDirectory and ExtractToDirectory. Yo also have compression choices of NoCompression, Fastest, and Optimal.
One thing about it that struck me about your post was the concept of files (even archives) within archives. With the ZipArchive and ZipArchiveEntry classes you can now
ZipArchive:
Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Read)
For Each ntry as ZipArchiveEntry In zippedFile.Entries
Debug.Writeline("entry " & ntry.FullName & " is only " & ntry.CompressedLength.ToString)
Next
End Using
Your question also was about adding to an existing archive. You can now do that like this:
Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Update)
zippedFile.createEntry("bar.txt", CompressionLevel.Fastest)
' likewise you can get an entry already in there...
Dim ntry As ZipArchiveEntry = zippedFile.GetEntry("wtf.doc")
' even delete an entry without need to decompress & compress again!
ntry.Delete() ' !
End Using
Again, this was a while ago, but a lot of us still use 2012, and as this change won't be going anywhere in future versions, it should still prove helpful moving forward if anyone hits in on a keyword/tag search...
...and we didn't even talk about UTF-8 support!
You probably aren't referencing System.IO.Compression. Check the box for that assembly reference and it should eliminate the error.
As mentioned in https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx
You can use ZipFile.ExtractToDirectory and CreateFromDirectory
This is the example:
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim startPath As String = "c:\example\start"
Dim zipPath As String = "c:\example\result.zip"
Dim extractPath As String = "c:\example\extract"
ZipFile.CreateFromDirectory(startPath, zipPath)
ZipFile.ExtractToDirectory(zipPath, extractPath)
End Sub
End Module
Make sure you have referenced System.IO.Compression.FileSystem for using this function.
Dim fileStream As Stream = File.OpenRead("your file path")
Using zipToOpen As FileStream = New FileStream(".......\My.zip", FileMode.CreateNew)
Using archive As ZipArchive = New ZipArchive(zipToOpen, ZipArchiveMode.Create)
Dim readmeEntry As ZipArchiveEntry = archive.CreateEntry("your file path")
fileStream.CopyTo(readmeEntry.Open())
End Using
End Using