Zip new file in VB: File is being used by another procces - vb.net

Hi folks I'm trying to zip file from a path to another path using ZipArchive and ZipFile but I can't achieve it.
zipped = "C:\Images\zip\file01.ZIP"
file = "C:\Images\file01.BAK"
Using newFile As ZipArchive = ZipFile.Open(zipped, ZipArchiveMode.Create)
newFile.CreateEntryFromFile(zipped, file, CompressionLevel.Optimal)
End Using
I'm getting the error: "C:\Images\zip\file01.ZIP" File is being used by another proccess
I will appreciate the help

Try archive mode Update instead of Create for a new entry in a zip archive from an existing file
zipped = "C:\Images\zip\file01.ZIP"
file = "C:\Images\file01.BAK"
Using newFile As ZipArchive = ZipFile.Open(zipped, ZipArchiveMode.Update)
newFile.CreateEntryFromFile(zipped, file, CompressionLevel.Optimal)
End Using

Related

Define exe output folder path

I have .exe file which generate .csv file in the same location as .exe file.
when I run my vb.net code .csv file is not generate in .exe file location but in location where my compiled vb.net exe code is runned.
how can I define .exe output csv file folder path?
I use this code in vb.net
Dim psi As New ProcessStartInfo
psi.FileName = "E:\Downlaoder.exe"
psi.Verb = "runas"
Process.Start(psi).WaitForExit()
If your program doesn't change the startup directory by itself then you should specify the WorkingDirectory when you define the ProcessStartInfo instance
Dim psi As New ProcessStartInfo
psi.FileName = "E:\Downlaoder.exe"
psi.WorkingDirectory = "E:\" ' This if you want the file to be created in E root.
You could use Directory.GetCurrentDirectory and use it as the path to save the file to the exe directory

Extracting from your resources VB.net

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.

Zip and unzip files

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

Open a file from a remote network share

I am trying to open a file from a server
I currently have
Dim attachedFilePath As String = "\\myserver\myshare\test.txt"
File.Open(attachedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)
This does not open a file.
However, if I change the path to be local then there is no issue.
Dim attachedFilePath As String = "c:\...\test.txt"
So, is there a way to open a file from remote storage?
File.Open is for reading the contents of a file. Use Process.Start to launch the default application for that file type
Dim Path = "\\myserver\myshare\test.txt"
System.Diagnostics.Process.Start(Path)

how to Zip files in vb.net 2005 [closed]

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)