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.
Related
I'm writing some program in VB, and I want to create txt file with text from file in resources. You didn't understood, did you? So, it goes like this.
Dim path As String = "c:\temp\MyTest.txt"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
is code for creating txt file with certain text. But, I need the following.
Dim fd As New FolderBrowserDialog
fd.ShowDialog()
is the only function that I have in program, and, when folder is selected, I need to create file in that folder, file's name should be config.cfg, but, text in file which is going to be created in selected folder should be text from mine txt file which is in Recources.
I've tried
Dim path As String = fd.SelectedPath
Dim fs As FileStream = File.Create(path)
' upisuje tekst u fajl
Dim info As Byte() = New UTF8Encoding(True).GetBytes(application.startuppath & "\..\..\Resources\config.cfg")
fs.Write(info, 0, info.Length)
fs.Close()
but the text I got in file is directory from where is my program debugged.
Any ideas to do this? :)
If you added a text file to your resources, then you can try something like this:
Using fbd As New FolderBrowserDialog
If fbd.ShowDialog(Me) = DialogResult.OK Then
File.WriteAllText(Path.Combine(fbd.SelectedPath, "config.cfg"), My.Resources.config)
End If
End Using
The file I added was called config, and it made a config.txt file in my resource library.
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
I am working on vb.net win form. My task is display the file names from a folder onto gridview control. when user clicks process button in my UI, all the file names present in gridview, the corresponding file has to be loaded onto memory stream buffer one after another and append the titles to the content of the file and save it in hard drive with _ed as a suffix to the file name.
I am very basic programmer. I have done the following attempt and succeeded in displaying filenames onto gridview. But no idea of later part. Any suggestions please?
'Displaying files from a folder onto a gridview
Dim inqueuePath As String = "C:\Users\Desktop\INQUEUE"
Dim fileInfo() As String
Dim rowint As Integer = 0
Dim name As String
Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)
With Gridview1
.Columns.Add("Column 0", "FileName")
.AutoResizeColumns()
End With
For Each name In fileInfo
Gridview1.Rows.Add()
Dim filename As String = System.IO.Path.GetFileName(name)
Gridview1.Item(0, rowint).Value = filename
rowint = rowint + 1
Next
Thank you very much for spending your valuable time to read this post.
to read a file into a memorystream is quite easy, just have a look at the following example and you should be able to convert it to suite your needs:
Dim bData As Byte()
Dim br As BinaryReader = New BinaryReader(System.IO.File.OpenRead(Path))
bData = br.ReadBytes(br.BaseStream.Length)
Dim ms As MemoryStream = New MemoryStream(bData, 0, bData.Length)
ms.Write(bData, 0, bData.Length)
then just use the MemoryStream ms as you please. Just to clearify Path holds the full path and filename you want to read into your memorystream.
I have File Like "Sample.bak" and when I compress it to be "Sample.zip" I lose the file extension inside the zip file I meann when I open the compressed file I find "Sample" without any extension.
I use this code :
Dim name As String = Path.GetFileName(filePath).Replace(".Bak", "")
Dim source() As Byte = System.IO.File.ReadAllBytes(filePath)
Dim compressed() As Byte = ConvertToByteArray(source)
System.IO.File.WriteAllBytes(destination & name & ".Bak" & ".zip", compressed)
Or using this code :
Public Sub cmdCompressFile(ByVal FileName As String)
'Stream object that reads file contents
Dim streamObj As Stream = New StreamReader(FileName).BaseStream
'Allocate space in buffer according to the length of the file read
Dim buffer(streamObj.Length) As Byte
'Fill buffer
streamObj.Read(buffer, 0, buffer.Length)
streamObj.Close()
'File Stream object used to change the extension of a file
Dim compFile As System.IO.FileStream = File.Create(Path.ChangeExtension(FileName, "zip"))
'GZip object that compress the file
Dim zipStreamObj As New GZipStream(compFile, CompressionMode.Compress)
'Write to the Stream object from the buffer
zipStreamObj.Write(buffer, 0, buffer.Length)
zipStreamObj.Close()
End Sub
please I need to compress the file without loosing file extension inside compressed file.
thanks,
GZipStream compresses a stream of bytes, it does no more than that. It does not embed file info in the stream, so you need to embed it somewhere.
The easiest way to restore the file name is to name it with the original name e.g. Sample.bak.zip.
If that doesn't work for you can use SharpZipLib (samples here) which does the embedding of the file info for you.
If you don't want to go that either of thoes you can either create your own file format and embed the file info or you can try and implement the standard gzip format
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)