I have a program that extracts data from a database, sticks it into an Excel workbook, zips the file using the GZipStream class in the System.IO.Compression namespace and then e-mails it to various people both in and out of our organisation. It works fine but there is one anomoly that I have worked around but would like a better solution for so I have come prostrate to the fount of all knowledge, Woody’s Lounge.
I use this code for the compression of my Excel file
Private Sub Compress(ByVal filename As String)
‘ Open the file as a FileStream object.
Dim infile As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim count As Integer
Dim buffer(infile.Length – 1) As Byte
‘ Read the file to ensure it is readable.
count = infile.Read(buffer, 0, buffer.Length)
If count buffer.Length Then
infile.Close()
Throw New Exception(“Compression failed. Number of bytes read not equal to buffer size”)
End If
infile.Close()
‘ Create the memory stream to accept the compressed data
Dim ms As New MemoryStream()
‘ Use the newly created memory stream for the compressed data.
Dim compressedzipStream As New GZipStream(ms, CompressionMode.Compress, True)
compressedzipStream.Write(buffer, 0, buffer.Length)
‘ Close the Zip stream.
compressedzipStream.Close()
‘ The memory stream now contains the Zipped data
‘ Create the output stream for the new file.
IO.File.Delete(filename & “.zip”)
Dim outfile As New FileStream(filename & “.zip”, FileMode.Create, FileAccess.Write, FileShare.Write)
Dim outbuffer(ms.Length – 1) As Byte
‘ Position to the start of the memory stream.
ms.Position = 0
count = ms.Read(outbuffer, 0, ms.Length)
If count outbuffer.Length Then
Throw New Exception(“Error reading memory stream. Count(” & count.ToString & ” not equal to buffer size(” & outbuffer.Length.ToString & “)”)
End If
outfile.Write(outbuffer, 0, outbuffer.Length)
outfile.Close()
End Sub
Most of the code is straight out of the Help facility and it works fine creating a file called, for example, kevin.xls.zip from a file called kevin.xls. When you open the file (I use WinRar), the file inside the zip file is named the same as the zip file minus the .zip extension. You can then extract this file and open it with Excel without any problems. So, what’s my question?
I can’t for the life of me figure out how to compress a file and give the resulting zip file a different name. For example, I want to zip ‘Some Transactions for 01-November-2007.xls’ into a zip file called fred.zip. Actually, you can do that but when you open the resulting zip file the file inside is called fred.
Does anybody know how to do this?
Regards,
Kevin Bell