Problem When Compressing File using vb.net - vb.net

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

Related

Write File with text from resources visual basic

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.

how can I read a zip file to stream?

I have a method that gives a stream file and upload it to server.
I want read a zip file from my disk and put it into a stream file, then my method can upload it automatically.
I search too much but the results just helps me to read a text file to stream! just like this:
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
but I want read a zip file to stream, not text file!

GZipstream cuts off data from original file when decompressing

For a long time I have been trying to debug why my parsing counts were off when downloading files to be parsed and been made to look really dumb about this. I did some debugging and found that the file I download when trying to decompress using GZipStream shows that it misses data from the original file. Here is my code for decompressing:
Using originalFileStream As FileStream = fileItem.OpenRead()
Dim currentFileName As String = fileItem.FullName
Dim newFileName = currentFileName.Remove(currentFileName.Length - fileItem.Extension.Length)
newFile = newFileName
Using decompressedFileStream As FileStream = File.Create(newFileName)
Using decompressionStream As GZipStream = New GZipStream(originalFileStream, CompressionMode.Decompress)
decompressionStream.CopyTo(decompressedFileStream)
Console.WriteLine("Decompressed: {0}", fileItem.Name)
decompressionStream.Close()
originalFileStream.Close()
End Using
End Using
End Using
Now what I do is return the newfile to the calling function and read the contents from there:
Dim responseData As String = inputFile.ReadToEnd
Now pasting the url in the browser and downloading from there and then opening using winrar I can see the data is not the same. Now this does not happen all the time as some files parse and decompress correctly. Each downloaded file has check counter to compare how many posts I am supposed to be parsing from it and that triggered me to see the mismatch in counts.
EDIT
Here is what I found in addition. If I read the problem file (as I said that only some files happen this way) by individual lines I will get all the data:
Dim rData As String = inputFile.ReadLine
If Not rData = "" Then
While Not inputFile.EndOfStream
rData = inputFile.ReadLine + vbNewLine + rData
End While
getIndividualPosts(rData)
End If
Now if I try to read an individual line from a file that is not problematic it will return nothing and so I will have to readtoEnd. Can anyone explain this odd behavior and is it related to the GZIPSTREAM or some error in my code.

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.

how to load a file from folder to memory stream buffer

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.