jean55 jean55 - 1 year ago 150 Question

Zip Files in .Net 4.5 without 3rd party libraries

I have a windows form (made with vb) where the business user can enter document numbers in a multi line textbox, each number can have one to many documents under that number i.e. if they enter 12345 then the gridview will display the 4 documents (the name of the documents and the description) that correspond to that document number.

Now I figured out how to parse the document numbers since if they want to enter more than one they need to separate by a comma (thanks to stackoverflow :D!) so I have this list of document names and I have searched this site but I cant understand how to loop through that list of document names from my directory and zip them to a folder without 3rd party libraries like dotnet etc since I am not allowed.

I know about .NET's static (? not sure if the right term) class "zipfile" and "ziparchive" with system.IO and system.IO.compression but looking at the msdn website and answers on here I found answers relating to writing lines in a file to add to a zipfile folder or creating them in the folder.

So my question is, is there anyway where I can loop through that list of document names and create a zipfile folder and add them to the created zipfile folder? So far I got this far in regards to zip paths I got the document name and path for each "file" in the list shown below( which I talked about above):

Dim values As String = TextBox1.Text.Replace(" ", ",")
Dim DocNum As String() = values.Trim().Split(","c)
Dim fullitems As String
For Each s As String In DocNum
Dim files() As String = Directory.GetFiles("\\folder path" & s)
If files.Length > 0 Then
For i As Integer = 0 To files.Length - 1
fullitems = files(i).ToString
Next i
End If

Any advice or direction on how to go in adding documents from a folder to a zipfile folder in .net with vb is appreciated!

Answer Source

I want to create a zip folder and add existing files (in this case documents) to the .zip folder, is that possible?

Yes it is possible. First you need to add a few references to your project.

  • System.IO.Compression
  • System.IO.Compression.FileSystem

Next, add these Import statements to your class file.

 Imports System.IO
 Imports System.IO.Compression

I used a button click event to do this, but you can put anywhere you would like to...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using modFile As ZipArchive = ZipFile.Open("ZIP PATH HERE", ZipArchiveMode.Update)
            modFile.CreateEntryFromFile("FILE YOU WANT TO ADD", "ENTRY NAME")
        End Using
    End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download