elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [problema]zipstorer traducida a vb.net
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [problema]zipstorer traducida a vb.net  (Leído 2,140 veces)
_katze_

Desconectado Desconectado

Mensajes: 140



Ver Perfil WWW
[problema]zipstorer traducida a vb.net
« en: 24 Junio 2011, 09:32 am »

hola a todos traduci de c-sharp una clase de compresion zip a vb.net por lo que asi la necesito se las paso pero tengo un problema al usarla en un procedimiento que se llama addstream para que busquen y quisiera saber porque me da ese error siendo que c-shar funciona a la perfeccion gracias..luego de arreglarla pueden usarla todos :P

Código
  1. Imports System.Collections.Generic
  2. Imports System.Text
  3. Imports System.IO.Compression
  4. Imports System.IO
  5. Namespace Compression
  6.    ''' <summary>
  7.    ''' Unique class for compression/decompression file. Represents a Zip file.
  8.    ''' </summary>
  9.    Public Class ZipStorer
  10.        Implements IDisposable
  11.        ''' <summary>
  12.        ''' Compression method enumeration
  13.        ''' </summary>
  14.        Public Enum Compression As UShort
  15.            ''' <summary>Uncompressed storage</summary>
  16.            Store = 0
  17.            ''' <summary>Deflate compression method</summary>
  18.            Deflate = 8
  19.        End Enum
  20.  
  21.        ''' <summary>
  22.        ''' Represents an entry in Zip file directory
  23.        ''' </summary>
  24.        Public Structure ZipFileEntry
  25.            ''' <summary>Compression method</summary>
  26.            Public Method As Compression
  27.            ''' <summary>Full path and filename as stored in Zip</summary>
  28.            Public FilenameInZip As String
  29.            ''' <summary>Original file size</summary>
  30.            Public FileSize As UInteger
  31.            ''' <summary>Compressed file size</summary>
  32.            Public CompressedSize As UInteger
  33.            ''' <summary>Offset of header information inside Zip storage</summary>
  34.            Public HeaderOffset As UInteger
  35.            ''' <summary>Offset of file inside Zip storage</summary>
  36.            Public FileOffset As UInteger
  37.            ''' <summary>Size of header information</summary>
  38.            Public HeaderSize As UInteger
  39.            ''' <summary>32-bit checksum of entire file</summary>
  40.            Public Crc32 As UInteger
  41.            ''' <summary>Last modification time of file</summary>
  42.            Public ModifyTime As DateTime
  43.            ''' <summary>User comment for file</summary>
  44.            Public Comment As String
  45.            ''' <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
  46.            Public EncodeUTF8 As Boolean
  47.  
  48.            ''' <summary>Overriden method</summary>
  49.            ''' <returns>Filename in Zip</returns>
  50.            Public Overrides Function ToString() As String
  51.                Return Me.FilenameInZip
  52.            End Function
  53.        End Structure
  54.  
  55. #Region "Public fields"
  56.        ''' <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
  57.        Public EncodeUTF8 As Boolean = False
  58.        ''' <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary>
  59.        Public ForceDeflating As Boolean = False
  60. #End Region
  61.  
  62. #Region "Private fields"
  63.        ' List of files to store
  64.        Private Files As New List(Of ZipFileEntry)()
  65.        ' Filename of storage file
  66.        Private FileName As String
  67.        ' Stream object of storage file
  68.        Private ZipFileStream As Stream
  69.  
  70.        ' General comment
  71.        Private Comment As String = ""
  72.        ' Central dir image
  73.        Private CentralDirImage As Byte() = Nothing
  74.        ' Existing files in zip
  75.        Private ExistingFiles As UShort = 0
  76.        ' File access for Open method
  77.        Private Access As FileAccess
  78.        ' Static CRC32 Table
  79.        Private Shared CrcTable As UInt32() = Nothing
  80.        ' Default filename encoder
  81.        Private Shared DefaultEncoding As Encoding = Encoding.GetEncoding(437)
  82. #End Region
  83.  
  84. #Region "Public methods"
  85.        ' Static constructor. Just invoked once in order to create the CRC32 lookup table.
  86.        Shared Sub New()
  87.            ' Generate CRC32 table
  88.            CrcTable = New UInt32(255) {}
  89.            For i As Integer = 0 To CrcTable.Length - 1
  90.                Dim c As UInt32 = CType(i, UInt32)
  91.                For j As Integer = 0 To 7
  92.                    If Not (c And 1) = 0 Then
  93.                        c = 3988292384UI Xor (c >> 1)
  94.                    Else
  95.                        c >>= 1
  96.                    End If
  97.                Next
  98.  
  99.                CrcTable(i) = c
  100.            Next
  101.  
  102.        End Sub
  103.        ''' <summary>
  104.        ''' Method to create a new storage file
  105.        ''' </summary>
  106.        ''' <param name="_filename">Full path of Zip file to create</param>
  107.        ''' <param name="_comment">General comment for Zip file</param>
  108.        ''' <returns>A valid ZipStorer object</returns>
  109.        Public Function Create(ByVal _filename As String, ByVal _comment As String) As ZipStorer
  110.            Dim file As New FileStream(_filename, FileMode.Create, FileAccess.ReadWrite)
  111.  
  112.            Dim stream As Stream = file
  113.  
  114.            Dim zip As ZipStorer = Create(stream, _comment)
  115.            zip.Comment = _comment
  116.            zip.FileName = _filename
  117.  
  118.            Return zip
  119.        End Function
  120.        ''' <summary>
  121.        ''' Method to create a new zip storage in a stream
  122.        ''' </summary>
  123.        ''' <param name="_stream"></param>
  124.        ''' <param name="_comment"></param>
  125.        ''' <returns>A valid ZipStorer object</returns>
  126.        Public Function Create(ByVal _stream As Stream, ByVal _comment As String) As ZipStorer
  127.            Dim zip As New ZipStorer()
  128.            zip.Comment = _comment
  129.            zip.ZipFileStream = _stream
  130.            zip.Access = FileAccess.Write
  131.  
  132.            Return zip
  133.        End Function
  134.        ''' <summary>
  135.        ''' Method to open an existing storage file
  136.        ''' </summary>
  137.        ''' <param name="_filename">Full path of Zip file to open</param>
  138.        ''' <param name="_access">File access mode as used in FileStream constructor</param>
  139.        ''' <returns>A valid ZipStorer object</returns>
  140.        Public Shared Function Open(ByVal _filename As String, ByVal _access As FileAccess) As ZipStorer
  141.            Dim stream As Stream = DirectCast(New FileStream(_filename, FileMode.Open, If(_access = FileAccess.Read, FileAccess.Read, FileAccess.ReadWrite)), Stream)
  142.  
  143.            Dim zip As ZipStorer = Open(stream, _access)
  144.            zip.FileName = _filename
  145.  
  146.            Return zip
  147.        End Function
  148.        ''' <summary>
  149.        ''' Method to open an existing storage from stream
  150.        ''' </summary>
  151.        ''' <param name="_stream">Already opened stream with zip contents</param>
  152.        ''' <param name="_access">File access mode for stream operations</param>
  153.        ''' <returns>A valid ZipStorer object</returns>
  154.        Public Shared Function Open(ByVal _stream As Stream, ByVal _access As FileAccess) As ZipStorer
  155.            If Not _stream.CanSeek AndAlso _access <> FileAccess.Read Then
  156.                Throw New InvalidOperationException("Stream cannot seek")
  157.            End If
  158.  
  159.            Dim zip As New ZipStorer()
  160.            'zip.FileName = _filename;
  161.            zip.ZipFileStream = _stream
  162.            zip.Access = _access
  163.  
  164.            If zip.ReadFileInfo() Then
  165.                Return zip
  166.            End If
  167.  
  168.            Throw New InvalidDataException()
  169.        End Function
  170.        ''' <summary>
  171.        ''' Add full contents of a file into the Zip storage
  172.        ''' </summary>
  173.        ''' <param name="_method">Compression method</param>
  174.        ''' <param name="_pathname">Full path of file to add to Zip storage</param>
  175.        ''' <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
  176.        ''' <param name="_comment">Comment for stored file</param>        
  177.        Public Sub AddFile(ByVal _method As Compression, ByVal _pathname As String, ByVal _filenameInZip As String, ByVal _comment As String)
  178.            If Access = FileAccess.Read Then
  179.                Throw New InvalidOperationException("Writing is not alowed")
  180.            End If
  181.  
  182.            Dim stream As New FileStream(_pathname, FileMode.Open, FileAccess.Read)
  183.            AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment)
  184.            stream.Close()
  185.        End Sub
  186.        ''' <summary>
  187.        ''' Add full contents of a stream into the Zip storage
  188.        ''' </summary>
  189.        ''' <param name="_method">Compression method</param>
  190.        ''' <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
  191.        ''' <param name="_source">Stream object containing the data to store in Zip</param>
  192.        ''' <param name="_modTime">Modification time of the data to store</param>
  193.        ''' <param name="_comment">Comment for stored file</param>
  194.        Public Sub AddStream(ByVal _method As Compression, ByVal _filenameInZip As String, ByVal _source As Stream, ByVal _modTime As DateTime, ByVal _comment As String)
  195.            If Access = FileAccess.Read Then
  196.                Throw New InvalidOperationException("Writing is not alowed")
  197.            End If
  198.  
  199.            Dim offset As Long
  200.            If Me.Files.Count = 0 Then
  201.                offset = 0
  202.            Else
  203.                Dim last As ZipFileEntry = Me.Files(Me.Files.Count - 1)
  204.                offset = last.HeaderOffset + last.HeaderSize
  205.            End If
  206.  
  207.            ' Prepare the fileinfo
  208.            Dim zfe As New ZipFileEntry()
  209.            zfe.Method = _method
  210.            zfe.EncodeUTF8 = Me.EncodeUTF8
  211.            zfe.FilenameInZip = NormalizedFilename(_filenameInZip)
  212.            zfe.Comment = (If(_comment Is Nothing, "", _comment))
  213.  
  214.            ' Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
  215.            zfe.Crc32 = 0
  216.            ' to be updated later
  217.  
  218.            zfe.HeaderOffset = CUInt(ZipFileStream.Position)
  219.            ' offset within file of the start of this local record
  220.            zfe.ModifyTime = _modTime
  221.  
  222.            ' Write local header
  223.            WriteLocalHeader(zfe)
  224.            zfe.FileOffset = CUInt(ZipFileStream.Position)
  225.  
  226.            ' Write file to zip (store)
  227.            Store(zfe, _source)
  228.            _source.Close()
  229.  
  230.            Me.UpdateCrcAndSizes(zfe)
  231.  
  232.            Files.Add(zfe)
  233.        End Sub
  234.        ''' <summary>
  235.        ''' Updates central directory (if pertinent) and close the Zip storage
  236.        ''' </summary>
  237.        ''' <remarks>This is a required step, unless automatic dispose is used</remarks>
  238.        Public Sub Close()
  239.            If Me.Access <> FileAccess.Read Then
  240.                Dim centralOffset As UInteger = CUInt(Me.ZipFileStream.Position)
  241.                Dim centralSize As UInteger = 0
  242.  
  243.                If Me.CentralDirImage IsNot Nothing Then
  244.                    Me.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length)
  245.                End If
  246.  
  247.                For i As Integer = 0 To Files.Count - 1
  248.                    Dim pos As Long = Me.ZipFileStream.Position
  249.                    Me.WriteCentralDirRecord(Files(i))
  250.                    centralSize += CUInt(Me.ZipFileStream.Position - pos)
  251.                Next
  252.  
  253.                If Me.CentralDirImage IsNot Nothing Then
  254.                    Me.WriteEndRecord(centralSize + CUInt(CentralDirImage.Length), centralOffset)
  255.                Else
  256.                    Me.WriteEndRecord(centralSize, centralOffset)
  257.                End If
  258.            End If
  259.  
  260.            If Me.ZipFileStream IsNot Nothing Then
  261.                Me.ZipFileStream.Flush()
  262.                Me.ZipFileStream.Dispose()
  263.                Me.ZipFileStream = Nothing
  264.            End If
  265.        End Sub
  266.        ''' <summary>
  267.        ''' Read all the file records in the central directory
  268.        ''' </summary>
  269.        ''' <returns>List of all entries in directory</returns>
  270.        Public Function ReadCentralDir() As List(Of ZipFileEntry)
  271.            If Me.CentralDirImage Is Nothing Then
  272.                Throw New InvalidOperationException("Central directory currently does not exist")
  273.            End If
  274.  
  275.            Dim result As New List(Of ZipFileEntry)()
  276.  
  277.            Dim pointer As Integer = 0
  278.            While pointer < Me.CentralDirImage.Length
  279.                Dim signature As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer)
  280.                If signature <> &H2014B50 Then
  281.                    Exit While
  282.                End If
  283.  
  284.                Dim encodeUTF8 As Boolean = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) And &H800) <> 0
  285.                Dim method As UShort = BitConverter.ToUInt16(CentralDirImage, pointer + 10)
  286.                Dim modifyTime As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer + 12)
  287.                Dim crc32 As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer + 16)
  288.                Dim comprSize As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer + 20)
  289.                Dim fileSize As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer + 24)
  290.                Dim filenameSize As UShort = BitConverter.ToUInt16(CentralDirImage, pointer + 28)
  291.                Dim extraSize As UShort = BitConverter.ToUInt16(CentralDirImage, pointer + 30)
  292.                Dim commentSize As UShort = BitConverter.ToUInt16(CentralDirImage, pointer + 32)
  293.                Dim headerOffset As UInteger = BitConverter.ToUInt32(CentralDirImage, pointer + 42)
  294.                Dim headerSize As UInteger = CUInt(46 + filenameSize + extraSize + commentSize)
  295.  
  296.                Dim encoder As Encoding = If(encodeUTF8, Encoding.UTF8, DefaultEncoding)
  297.  
  298.                Dim zfe As New ZipFileEntry()
  299.                zfe.Method = CType(method, Compression)
  300.                zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize)
  301.                zfe.FileOffset = GetFileOffset(headerOffset)
  302.                zfe.FileSize = fileSize
  303.                zfe.CompressedSize = comprSize
  304.                zfe.HeaderOffset = headerOffset
  305.                zfe.HeaderSize = headerSize
  306.                zfe.Crc32 = crc32
  307.                zfe.ModifyTime = DosTimeToDateTime(modifyTime)
  308.                If commentSize > 0 Then
  309.                    zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize)
  310.                End If
  311.  
  312.                result.Add(zfe)
  313.                pointer += (46 + filenameSize + extraSize + commentSize)
  314.            End While
  315.  
  316.            Return result
  317.        End Function
  318.        ''' <summary>
  319.        ''' Copy the contents of a stored file into a physical file
  320.        ''' </summary>
  321.        ''' <param name="_zfe">Entry information of file to extract</param>
  322.        ''' <param name="_filename">Name of file to store uncompressed data</param>
  323.        ''' <returns>True if success, false if not.</returns>
  324.        ''' <remarks>Unique compression methods are Store and Deflate</remarks>
  325.        Public Function ExtractFile(ByVal _zfe As ZipFileEntry, ByVal _filename As String) As Boolean
  326.            ' Make sure the parent directory exist
  327.            Dim paths As String = Path.GetDirectoryName(_filename)
  328.  
  329.            If Not Directory.Exists(paths) Then
  330.                Directory.CreateDirectory(paths)
  331.            End If
  332.            ' Check it is directory. If so, do nothing
  333.            If Directory.Exists(_filename) Then
  334.                Return True
  335.            End If
  336.  
  337.            Dim output As Stream = New FileStream(_filename, FileMode.Create, FileAccess.Write)
  338.            Dim result As Boolean = ExtractFile(_zfe, output)
  339.            If result Then
  340.                output.Close()
  341.            End If
  342.  
  343.            File.SetCreationTime(_filename, _zfe.ModifyTime)
  344.            File.SetLastWriteTime(_filename, _zfe.ModifyTime)
  345.  
  346.            Return result
  347.        End Function
  348.        ''' <summary>
  349.        ''' Copy the contents of a stored file into an opened stream
  350.        ''' </summary>
  351.        ''' <param name="_zfe">Entry information of file to extract</param>
  352.        ''' <param name="_stream">Stream to store the uncompressed data</param>
  353.        ''' <returns>True if success, false if not.</returns>
  354.        ''' <remarks>Unique compression methods are Store and Deflate</remarks>
  355.        Public Function ExtractFile(ByVal _zfe As ZipFileEntry, ByVal _stream As Stream) As Boolean
  356.            If Not _stream.CanWrite Then
  357.                Throw New InvalidOperationException("Stream cannot be written")
  358.            End If
  359.  
  360.            ' check signature
  361.            Dim signature As Byte() = New Byte(3) {}
  362.            Me.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin)
  363.            Me.ZipFileStream.Read(signature, 0, 4)
  364.            If BitConverter.ToUInt32(signature, 0) <> &H4034B50 Then
  365.                Return False
  366.            End If
  367.  
  368.            ' Select input stream for inflating or just reading
  369.            Dim inStream As Stream
  370.            If _zfe.Method = Compression.Store Then
  371.                inStream = Me.ZipFileStream
  372.            ElseIf _zfe.Method = Compression.Deflate Then
  373.                inStream = New DeflateStream(Me.ZipFileStream, CompressionMode.Decompress, True)
  374.            Else
  375.                Return False
  376.            End If
  377.  
  378.            ' Buffered copy
  379.            Dim buffer As Byte() = New Byte(16383) {}
  380.            Me.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin)
  381.            Dim bytesPending As UInteger = _zfe.FileSize
  382.            While bytesPending > 0
  383.                Dim bytesRead As Integer = inStream.Read(buffer, 0, CInt(Math.Min(bytesPending, buffer.Length)))
  384.                _stream.Write(buffer, 0, bytesRead)
  385.                bytesPending -= CUInt(bytesRead)
  386.            End While
  387.            _stream.Flush()
  388.  
  389.            If _zfe.Method = Compression.Deflate Then
  390.                inStream.Dispose()
  391.            End If
  392.            Return True
  393.        End Function
  394.        ''' <summary>
  395.        ''' Removes one of many files in storage. It creates a new Zip file.
  396.        ''' </summary>
  397.        ''' <param name="_zip">Reference to the current Zip object</param>
  398.        ''' <param name="_zfes">List of Entries to remove from storage</param>
  399.        ''' <returns>True if success, false if not</returns>
  400.        ''' <remarks>This method only works for storage of type FileStream</remarks>
  401.        Public Function RemoveEntries(ByRef _zip As ZipStorer, ByVal _zfes As List(Of ZipFileEntry)) As Boolean
  402.            If Not (TypeOf _zip.ZipFileStream Is FileStream) Then
  403.                Throw New InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream")
  404.            End If
  405.  
  406.  
  407.            'Get full list of entries
  408.            Dim fullList As List(Of ZipFileEntry) = _zip.ReadCentralDir()
  409.  
  410.            'In order to delete we need to create a copy of the zip file excluding the selected items
  411.            Dim tempZipName As String = Path.GetTempFileName()
  412.            Dim tempEntryName As String = Path.GetTempFileName()
  413.  
  414.            Try
  415.                Dim tempZip As ZipStorer = Create(tempZipName, String.Empty)
  416.  
  417.                For Each zfe As ZipFileEntry In fullList
  418.                    If Not _zfes.Contains(zfe) Then
  419.                        If _zip.ExtractFile(zfe, tempEntryName) Then
  420.                            tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment)
  421.                        End If
  422.                    End If
  423.                Next
  424.                _zip.Close()
  425.                tempZip.Close()
  426.  
  427.                File.Delete(_zip.FileName)
  428.                File.Move(tempZipName, _zip.FileName)
  429.  
  430.                _zip = ZipStorer.Open(_zip.FileName, _zip.Access)
  431.            Catch
  432.                Return False
  433.            Finally
  434.                If File.Exists(tempZipName) Then
  435.                    File.Delete(tempZipName)
  436.                End If
  437.                If File.Exists(tempEntryName) Then
  438.                    File.Delete(tempEntryName)
  439.                End If
  440.            End Try
  441.            Return True
  442.        End Function
  443. #End Region
  444.  
  445. #Region "Private methods"
  446.        ' Calculate the file offset by reading the corresponding local header
  447.        Private Function GetFileOffset(ByVal _headerOffset As UInteger) As UInteger
  448.            Dim buffer As Byte() = New Byte(1) {}
  449.  
  450.            Me.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin)
  451.            Me.ZipFileStream.Read(buffer, 0, 2)
  452.            Dim filenameSize As UShort = BitConverter.ToUInt16(buffer, 0)
  453.            Me.ZipFileStream.Read(buffer, 0, 2)
  454.            Dim extraSize As UShort = BitConverter.ToUInt16(buffer, 0)
  455.  
  456.            Return CUInt(30 + filenameSize + extraSize + _headerOffset)
  457.        End Function
  458.        ' Local file header:
  459.        '            local file header signature     4 bytes  (0x04034b50)
  460.        '            version needed to extract       2 bytes
  461.        '            general purpose bit flag        2 bytes
  462.        '            compression method              2 bytes
  463.        '            last mod file time              2 bytes
  464.        '            last mod file date              2 bytes
  465.        '            crc-32                          4 bytes
  466.        '            compressed size                 4 bytes
  467.        '            uncompressed size               4 bytes
  468.        '            filename length                 2 bytes
  469.        '            extra field length              2 bytes
  470.        '
  471.        '            filename (variable size)
  472.        '            extra field (variable size)
  473.        '        
  474.  
  475.        Private Sub WriteLocalHeader(ByRef _zfe As ZipFileEntry)
  476.            Dim pos As Long = Me.ZipFileStream.Position
  477.            Dim encoder As Encoding = If(_zfe.EncodeUTF8, Encoding.UTF8, DefaultEncoding)
  478.            Dim encodedFilename As Byte() = encoder.GetBytes(_zfe.FilenameInZip)
  479.  
  480.            Me.ZipFileStream.Write(New Byte() {80, 75, 3, 4, 20, 0}, 0, 6)
  481.            ' No extra header
  482.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(If(_zfe.EncodeUTF8, &H800, 0))), 0, 2)
  483.            ' filename and comment encoding
  484.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(_zfe.Method)), 0, 2)
  485.            ' zipping method
  486.            Me.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4)
  487.            ' zipping date and time
  488.            Me.ZipFileStream.Write(New Byte() {0, 0, 0, 0, 0, 0, _
  489.             0, 0, 0, 0, 0, 0}, 0, 12)
  490.            ' unused CRC, un/compressed size, updated later
  491.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(encodedFilename.Length)), 0, 2)
  492.            ' filename length
  493.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(0)), 0, 2)
  494.            ' extra length
  495.            Me.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length)
  496.            _zfe.HeaderSize = CUInt(Me.ZipFileStream.Position - pos)
  497.        End Sub
  498.        ' Central directory's File header:
  499.        '            central file header signature   4 bytes  (0x02014b50)
  500.        '            version made by                 2 bytes
  501.        '            version needed to extract       2 bytes
  502.        '            general purpose bit flag        2 bytes
  503.        '            compression method              2 bytes
  504.        '            last mod file time              2 bytes
  505.        '            last mod file date              2 bytes
  506.        '            crc-32                          4 bytes
  507.        '            compressed size                 4 bytes
  508.        '            uncompressed size               4 bytes
  509.        '            filename length                 2 bytes
  510.        '            extra field length              2 bytes
  511.        '            file comment length             2 bytes
  512.        '            disk number start               2 bytes
  513.        '            internal file attributes        2 bytes
  514.        '            external file attributes        4 bytes
  515.        '            relative offset of local header 4 bytes
  516.        '
  517.        '            filename (variable size)
  518.        '            extra field (variable size)
  519.        '            file comment (variable size)
  520.        '        
  521.  
  522.        Private Sub WriteCentralDirRecord(ByVal _zfe As ZipFileEntry)
  523.            Dim encoder As Encoding = If(_zfe.EncodeUTF8, Encoding.UTF8, DefaultEncoding)
  524.            Dim encodedFilename As Byte() = encoder.GetBytes(_zfe.FilenameInZip)
  525.            Dim encodedComment As Byte() = encoder.GetBytes(_zfe.Comment)
  526.  
  527.            Me.ZipFileStream.Write(New Byte() {80, 75, 1, 2, 23, &HB, _
  528.             20, 0}, 0, 8)
  529.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(If(_zfe.EncodeUTF8, &H800, 0))), 0, 2)
  530.            ' filename and comment encoding
  531.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(_zfe.Method)), 0, 2)
  532.            ' zipping method
  533.            Me.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4)
  534.            ' zipping date and time
  535.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4)
  536.            ' file CRC
  537.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4)
  538.            ' compressed file size
  539.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4)
  540.            ' uncompressed file size
  541.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(encodedFilename.Length)), 0, 2)
  542.            ' Filename in zip
  543.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(0)), 0, 2)
  544.            ' extra length
  545.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(encodedComment.Length)), 0, 2)
  546.  
  547.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(0)), 0, 2)
  548.            ' disk=0
  549.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(0)), 0, 2)
  550.            ' file type: binary
  551.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(0)), 0, 2)
  552.            ' Internal file attributes
  553.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(&H8100)), 0, 2)
  554.            ' External file attributes (normal/readable)
  555.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4)
  556.            ' Offset of header
  557.            Me.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length)
  558.            Me.ZipFileStream.Write(encodedComment, 0, encodedComment.Length)
  559.        End Sub
  560.        ' End of central dir record:
  561.        '            end of central dir signature    4 bytes  (0x06054b50)
  562.        '            number of this disk             2 bytes
  563.        '            number of the disk with the
  564.        '            start of the central directory  2 bytes
  565.        '            total number of entries in
  566.        '            the central dir on this disk    2 bytes
  567.        '            total number of entries in
  568.        '            the central dir                 2 bytes
  569.        '            size of the central directory   4 bytes
  570.        '            offset of start of central
  571.        '            directory with respect to
  572.        '            the starting disk number        4 bytes
  573.        '            zipfile comment length          2 bytes
  574.        '            zipfile comment (variable size)
  575.        '        
  576.  
  577.        Private Sub WriteEndRecord(ByVal _size As UInteger, ByVal _offset As UInteger)
  578.            Dim encoder As Encoding = If(Me.EncodeUTF8, Encoding.UTF8, DefaultEncoding)
  579.            Dim encodedComment As Byte() = encoder.GetBytes(Me.Comment)
  580.  
  581.            Me.ZipFileStream.Write(New Byte() {80, 75, 5, 6, 0, 0, _
  582.             0, 0}, 0, 8)
  583.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(Files.Count) + ExistingFiles), 0, 2)
  584.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(Files.Count) + ExistingFiles), 0, 2)
  585.            Me.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4)
  586.            Me.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4)
  587.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(encodedComment.Length)), 0, 2)
  588.            Me.ZipFileStream.Write(encodedComment, 0, encodedComment.Length)
  589.        End Sub
  590.        ' Copies all source file into storage file
  591.        Private Sub Store(ByRef _zfe As ZipFileEntry, ByVal _source As Stream)
  592.            Dim buffer As Byte() = New Byte(16383) {}
  593.            Dim bytesRead As Integer
  594.            Dim totalRead As UInteger = 0
  595.            Dim outStream As Stream
  596.  
  597.            Dim posStart As Long = Me.ZipFileStream.Position
  598.            Dim sourceStart As Long = _source.Position
  599.  
  600.            If _zfe.Method = Compression.Store Then
  601.                outStream = Me.ZipFileStream
  602.            Else
  603.                outStream = New DeflateStream(Me.ZipFileStream, CompressionMode.Compress, True)
  604.            End If
  605.  
  606.            _zfe.Crc32 = 0 Xor &HFFFFFFFFUI
  607.  
  608.            Do
  609.                bytesRead = _source.Read(buffer, 0, buffer.Length)
  610.                totalRead += CUInt(bytesRead)
  611.                If bytesRead > 0 Then
  612.                    outStream.Write(buffer, 0, bytesRead)
  613.  
  614.                    For i As UInteger = 0 To bytesRead - 1
  615.                        _zfe.Crc32 = ZipStorer.CrcTable((_zfe.Crc32 Xor buffer(i)) And &HFF) Xor (_zfe.Crc32 >> 8)
  616.                    Next
  617.                End If
  618.            Loop While bytesRead = buffer.Length
  619.            outStream.Flush()
  620.  
  621.            If _zfe.Method = Compression.Deflate Then
  622.                outStream.Dispose()
  623.            End If
  624.  
  625.            _zfe.Crc32 = _zfe.Crc32 Xor &HFFFFFFFFUI
  626.            _zfe.FileSize = totalRead
  627.            _zfe.CompressedSize = CUInt(Me.ZipFileStream.Position - posStart)
  628.  
  629.            ' Verify for real compression
  630.            If _zfe.Method = Compression.Deflate AndAlso Not Me.ForceDeflating AndAlso _source.CanSeek AndAlso _zfe.CompressedSize > _zfe.FileSize Then
  631.                ' Start operation again with Store algorithm
  632.                _zfe.Method = Compression.Store
  633.                Me.ZipFileStream.Position = posStart
  634.                Me.ZipFileStream.SetLength(posStart)
  635.                _source.Position = sourceStart
  636.                Me.Store(_zfe, _source)
  637.            End If
  638.        End Sub
  639.        ' DOS Date and time:
  640.        '            MS-DOS date. The date is a packed value with the following format. Bits Description
  641.        '                0-4 Day of the month (1–31)
  642.        '                5-8 Month (1 = January, 2 = February, and so on)
  643.        '                9-15 Year offset from 1980 (add 1980 to get actual year)
  644.        '            MS-DOS time. The time is a packed value with the following format. Bits Description
  645.        '                0-4 Second divided by 2
  646.        '                5-10 Minute (0–59)
  647.        '                11-15 Hour (0–23 on a 24-hour clock)
  648.        '        
  649.  
  650.        Private Function DateTimeToDosTime(ByVal _dt As DateTime) As UInteger
  651.            Return CUInt((_dt.Second \ 2) Or (_dt.Minute << 5) Or (_dt.Hour << 11) Or (_dt.Day << 16) Or (_dt.Month << 21) Or ((_dt.Year - 1980) << 25))
  652.        End Function
  653.        Private Function DosTimeToDateTime(ByVal _dt As UInteger) As DateTime
  654.            Return New DateTime(CInt(_dt >> 25) + 1980, CInt(_dt >> 21) And 15, CInt(_dt >> 16) And 31, CInt(_dt >> 11) And 31, CInt(_dt >> 5) And 63, CInt(_dt And 31) * 2)
  655.        End Function
  656.  
  657.        ' CRC32 algorithm
  658.        '          The 'magic number' for the CRC is 0xdebb20e3.  
  659.        '          The proper CRC pre and post conditioning
  660.        '          is used, meaning that the CRC register is
  661.        '          pre-conditioned with all ones (a starting value
  662.        '          of 0xffffffff) and the value is post-conditioned by
  663.        '          taking the one's complement of the CRC residual.
  664.        '          If bit 3 of the general purpose flag is set, this
  665.        '          field is set to zero in the local header and the correct
  666.        '          value is put in the data descriptor and in the central
  667.        '          directory.
  668.        '        
  669.  
  670.        Private Sub UpdateCrcAndSizes(ByRef _zfe As ZipFileEntry)
  671.            Dim lastPos As Long = Me.ZipFileStream.Position
  672.            ' remember position
  673.            Me.ZipFileStream.Position = _zfe.HeaderOffset + 8
  674.            Me.ZipFileStream.Write(BitConverter.GetBytes(CUShort(_zfe.Method)), 0, 2)
  675.            ' zipping method
  676.            Me.ZipFileStream.Position = _zfe.HeaderOffset + 14
  677.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4)
  678.            ' Update CRC
  679.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4)
  680.            ' Compressed size
  681.            Me.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4)
  682.            ' Uncompressed size
  683.            Me.ZipFileStream.Position = lastPos
  684.            ' restore position
  685.        End Sub
  686.        ' Replaces backslashes with slashes to store in zip header
  687.        Private Function NormalizedFilename(ByVal _filename As String) As String
  688.            Dim filename As String = _filename.Replace("\"c, "/"c)
  689.  
  690.            Dim pos As Integer = filename.IndexOf(":"c)
  691.            If pos >= 0 Then
  692.                filename = filename.Remove(0, pos + 1)
  693.            End If
  694.  
  695.            Return filename.Trim("/"c)
  696.        End Function
  697.        ' Reads the end-of-central-directory record
  698.        Private Function ReadFileInfo() As Boolean
  699.            If Me.ZipFileStream.Length < 22 Then
  700.                Return False
  701.            End If
  702.  
  703.            Try
  704.                Me.ZipFileStream.Seek(-17, SeekOrigin.[End])
  705.                Dim br As New BinaryReader(Me.ZipFileStream)
  706.                Do
  707.                    Me.ZipFileStream.Seek(-5, SeekOrigin.Current)
  708.                    Dim sig As UInt32 = br.ReadUInt32()
  709.                    If sig = &H6054B50 Then
  710.                        Me.ZipFileStream.Seek(6, SeekOrigin.Current)
  711.  
  712.                        Dim entries As UInt16 = br.ReadUInt16()
  713.                        Dim centralSize As Int32 = br.ReadInt32()
  714.                        Dim centralDirOffset As UInt32 = br.ReadUInt32()
  715.                        Dim commentSize As UInt16 = br.ReadUInt16()
  716.  
  717.                        ' check if comment field is the very last data in file
  718.                        If Me.ZipFileStream.Position + commentSize <> Me.ZipFileStream.Length Then
  719.                            Return False
  720.                        End If
  721.  
  722.                        ' Copy entire central directory to a memory buffer
  723.                        Me.ExistingFiles = entries
  724.                        Me.CentralDirImage = New Byte(centralSize - 1) {}
  725.                        Me.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin)
  726.                        Me.ZipFileStream.Read(Me.CentralDirImage, 0, centralSize)
  727.  
  728.                        ' Leave the pointer at the begining of central dir, to append new files
  729.                        Me.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin)
  730.                        Return True
  731.                    End If
  732.                Loop While Me.ZipFileStream.Position > 0
  733.            Catch
  734.            End Try
  735.  
  736.            Return False
  737.        End Function
  738. #End Region
  739.  
  740. #Region "IDisposable Members"
  741.        ''' <summary>
  742.        ''' Closes the Zip file stream
  743.        ''' </summary>
  744.        Public Sub Dispose() Implements IDisposable.Dispose
  745.            Me.Close()
  746.        End Sub
  747. #End Region
  748.    End Class
  749. End Namespace
  750.  


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problema BlueZScanner y problema de conexión
Hacking Mobile
Kasswed 3 6,289 Último mensaje 6 Mayo 2006, 22:04 pm
por Gospel
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines