Форум программистов, компьютерный форум, киберфорум
Visual Basic
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 5.00/1: Рейтинг темы: голосов - 1, средняя оценка - 5.00
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1

Работа с zip архивами

29.10.2024, 02:49. Показов 18760. Ответов 282
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Из всего, что попадалось по теме сжатия/распаковки ZIP наиболее интересные были примеры с использованием библиотеки Zlib. Оригинальная zlib использует cdecl экспорт функций, но есть реализация zlibwapi.dll, которую можно использовать в VB. Вот хороший пример использования. Там можно увидеть как сжть/распаковать массив байтов, но вот беда, очень сложно найти пример под VB с более обширным использованием, способной на большее, данной либы, которая не есть простая, там есть функции с использованием множества параметров констант и длинных структур, которые чтобы узнать наверное надо долго копатся в сишных заголочниках. Но HackerVlad в личной беседе говорил, что у него есть исходники с использованием данной библиотеки, поэтому любезно прошу его поделиться данной информацией.

Добавлено через 1 минуту
кстати словосочетание zip-архивами в названии форум блочит почему-то )

Добавлено через 6 минут
На одном форуме есть хороший пример испльзования функций zlib для извлечения/распаковки отдельных файлов, там
Кликните здесь для просмотра всего текста
обсуждался какой-то экзотический ЯП Clarion, но очень наглядно
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
! Источнег: https://forum.clarionlife.net/viewtopic.php?t=2389
! Для добавления в архив PwlZip ваш пароль
ZipHandle = zipOpen(NEW_ZIPPACK, 0)
If EncryptFlag = 1
Res# = zipOpenNewFileInZip3(ZipHandle, PATH_CURZIP, Zinfo, 0, 0, 0, 0, Comment, Z_DEFLATED, CompressionFlag,0,-15,8,0,PwlZip,0)
Else
Res# = zipOpenNewFileInZip(ZipHandle, PATH_CURZIP, Zinfo, 0, 0, 0, 0, Comment, Z_DEFLATED, CompressionFlag)
.
 
!Для чтения из архива
ZipHandle = unzOpen(PATH_INFILE_PACK)
LocRes1=UnzGoToFirstFile(ZipHandle)
If unzGetCurrentFileInfo(ZipHandle,FinFo,PATH_NAMEUPD_TMP,Size(PATH_NAMEUPD_TMP),0,0,Comment,Size(Comment)).
If FinFo.Flag = 3 !признак шифрованного zip по крайней мере так я понял после мыкания с архивами
LocRes2 = unzOpenCurrentFilePassword(ZipHandle,PwlZip)
Else
LocRes2 = UnzOpenCurrentFile(ZipHandle)

Здесь подробное описание функций, структур и констант, однако я не нашел там unzGetCurrentFileInfo и т.п.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
29.10.2024, 02:49
Ответы с готовыми решениями:

Работа с ZIP-архивами - распаковка файлов
Привет, уважаемый ALL! Подскажите, как можно работать с zip архивами из VBA? Стоит задача: 1) прочитать из архива...

Автоматизировать заполнение "Графика выполненных работ по месяцам"
Используя готовую рабочую книгу Blank1.xls, автоматизировать заполнение "Графика выполненных работ по месяцам". Из диапазона дат в...

Задания из лаб.работ
Надоедаю наверное уже всем...

282
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
29.10.2024, 17:15  [ТС]
Студворк — интернет-сервис помощи студентам
Да еще я упустил момент получения размера извлекаемого файла, скорее всего с помощью compressBound или deflateBound там всего две функции в экспорте со словом "Bound"
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 17:16
testuser2, посмотри по ссылке что я тебе дал, ты кстати и сам мог бы задать вопрос на иностранном форуме, видишь они даже быстро отвечают как я спросил
0
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
29.10.2024, 17:25  [ТС]
Сама функция возвращает размер распакованых байтов
Return Values

The number of uncompressed bytes that were read.
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 17:34
Обрати внимание на функцию:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'---------------------------------------------------------------------------------------
' Procedure : ExtractToMemory
' DateTime  : 18-11-2006
' Author    : ArnoutV
' Purpose   :
'---------------------------------------------------------------------------------------
Public Function ExtractToMemory(ByVal sExtractFile As String, bData() As Byte) As Boolean
  Dim l As Long
  Dim FilePos As Long
  Dim sFilename As String
   
  If Len(ZLibVersion) = 0 Then
     Exit Function
  End If
   
  If CentralDirEndPos = 0 Then
    RaiseEvent ZipError(zeNoOpenZipFile, "There is no Zip File Open")
    Exit Function
  End If
   
  sExtractFile = LCase$(sExtractFile)
  
  If ReadCentralDirEnd(CentralDirEndPos) Then
    Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
    
    For l = 1 To CentralDirEnd.EntriesInTheCentralDir
      ReadCentralFileHeader sFilename
      If LCase$(GetFileName(sFilename)) = sExtractFile Then
        If CentralFileHeader.UnCompressedSize > 0 Then
          FilePos = Seek(m_fID)
          ExtractToMemory = ExtractArray(sFilename, bData)
        End If
        Exit For
      End If
    Next l
  End If
 
End Function
0
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
29.10.2024, 17:44  [ТС]
HackerVlad, офигенно! У меня была кстати мысль, что там не одним методом все делать, там 121 функция, видимо кому как удобние. Тут вообще 5 функций используется и ни одной с префиксом zip или unz

Добавлено через 1 минуту
Цитата Сообщение от HackerVlad Посмотреть сообщение
Обрати внимание на функцию:
Да это хорошая функция, я ее тоже заметил
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 17:53
testuser2, всё идеально работает, я только что проверил. Спасибо конечно им, молодцы, выложили хороший класс для распаковки. Однако используются функции ни те что ты думал почему-то...

Да и кстати! Вуаля! Там тоже можно распаковывать сразу в байтовый массив при чём можно выбирать какой именно файл выдернуть из архива по FileName для того чтобы засунуть его в байтовый массив, прям как ты и хотел, прям как ты и мечтал. Прям твоя мечта сбылась с этим классом, что выложили.
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 18:37
Лучший ответ Сообщение было отмечено testuser2 как решение

Решение

Итак, я подготовил новое решение для этой очень интересной темы! Я написал простенькую программку для чтения картинок из ZIP файла, выбираешь из списка файл и картинка загружается. На лету! Никаких временных файлов! Всё идёт через байтовые массивы! Считывание файлов из ZIP идёт с помощью библиотеки zlibwapi.dll и с помощью класса, который нам любезно предоставил Arnoutdv.

Форма:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Option Explicit
Dim zip As New clsZipExtractionClass
Private Declare Function SafeArrayGetDim Lib "oleaut32.dll" (arr() As Any) As Long
 
Private Sub Command1_Click()
    Dim strArray() As String
    Dim i As Long
    
    zip.OpenZip App.Path & "\test.zip"
    
    strArray() = zip.GetFiles ' Получить список файлов внутри ZIP
    
    For i = 0 To UBound(strArray)
        List1.AddItem strArray(i)
    Next
    
    List1.Selected(0) = True
    Label1.Caption = "Count files: " & zip.Count
    List1.SetFocus
    
    zip.CloseZip
End Sub
 
Private Sub List1_Click()
    Dim bytesData() As Byte
    
    zip.OpenZip App.Path & "\test.zip"
    zip.ExtractToMemory List1.Text, bytesData
    zip.CloseZip
    
    If SafeArrayGetDim(bytesData) > 0 Then Picture1.Picture = PictureFromBits(bytesData)
End Sub
Класс clsZipExtractionClass:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
Option Explicit
 
Private m_fID As Integer
Private m_bOpenZip As Boolean
 
 
Private Const INVALID_HANDLE_VALUE As Long = -1
Private Const OPEN_EXISTING  As Long = 3
Private Const FILE_SHARE_READ  As Long = &H1
Private Const FILE_SHARE_WRITE  As Long = &H2
Private Const GENERIC_WRITE  As Long = &H40000000
Private Const GENERIC_READ As Long = &H80000000
Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
Private Const MAX_PATH As Long = 260
 
 
Private Type FILETIME
  dwLowDateTime As Long
  dwHighDateTime As Long
End Type
 
'Private Type SYSTEMTIME
'  Year As Integer
'  Month As Integer
'  DayOfWeek As Integer
'  Day As Integer
'  Hour As Integer
'  Minute As Integer
'  Second As Integer
'  Milliseconds As Integer
'End Type
 
Private Type WIN32_FIND_DATA
   dwFileAttributes As Long
   ftCreationTime As FILETIME
   ftLastAccessTime As FILETIME
   ftLastWriteTime As FILETIME
   nFileSizeHigh As Long
   nFileSizeLow As Long
   dwReserved0 As Long
   dwReserved1 As Long
   cFileName As String * MAX_PATH
   cAlternate As String * 14
End Type
 
 
Private Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Dest As Any, src As Any, ByVal Length As Long) As Long
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpBuffer As String, ByVal lpString As Long) As Long
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
 
Private Declare Function ZLibVer Lib "zlibwapi.dll" Alias "zlibVersion" () As Long
'Private Declare Function Compress Lib "zlibwapi.dll" Alias "compress" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
'Private Declare Function Compress2 Lib "zlibwapi.dll" Alias "compress2" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long, ByVal Level As Long) As Long
Private Declare Function Uncompress Lib "zlibwapi.dll" Alias "uncompress" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
Private Declare Function lCRC32 Lib "zlibwapi.dll" Alias "crc32" (ByVal crc As Long, Buffer As Any, ByVal Length As Long) As Long
 
Private Declare Function DosDateTimeToFileTime Lib "kernel32.dll" (ByVal wFatDate As Long, ByVal wFatTime As Long, lpFileTime As FILETIME) As Long
Private Declare Function LocalFileTimeToFileTime Lib "kernel32.dll" (lpLocalFileTime As FILETIME, lpFileTime As FILETIME) As Long
 
Private Declare Function SetFileTime Lib "kernel32" (ByVal hFile As Long, CreationTime As FILETIME, LastAccessTime As FILETIME, LastWriteTime As FILETIME) As Long
 
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
 
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
 
                 
Public Enum eZipError
  zeZLibNotInstalled = 1
  zeNotZipFile = 2
  zeNoOpenZipFile = 3
  zeUnsupportedCompressionMethod = 4
  zeChecksumError = 5
  zeFileNotFound = 10
  zeFileAlreadyExists = 11
  zeCantRemoveFile = 12
  zeCantCreateFolder = 13
  zeCantCreateFile = 14
End Enum
 
Private Type typCentralFileHeader
  CentralFileHeaderSigniature As Long
  VersionMadeBy As Integer
  VersionNeededToExtract As Integer
  GeneralPurposeBitFlag As Integer
  CompressionMethod As Integer
  LastModFileTime As Integer
  LastModFileDate As Integer
  CRC32 As Long
  CompressedSize As Long
  UnCompressedSize As Long
  FileNameLength As Integer
  ExtraFieldLength As Integer
  FileCommentLength As Integer
  DiskNumberStart As Integer
  InternalFileAttributes As Integer
  ExternalFileAttributes As Long
  RelativeOffsetOfLocalHeader As Long
End Type
 
Private Type typCenteralDirEnd
  EndOFCentralDirSignature As Long
  NumberOfThisDisk As Integer
  NumberOfDiskWithCentralDir As Integer
  EntriesInTheCentralDirThisOnDisk As Integer
  EntriesInTheCentralDir As Integer
  SizeOfCentralDir As Long
  OffSetOfCentralDir As Long
  ZipFileCommentLength As Integer
End Type
 
Private Type typLocalFileHeader
  LocalFileHeaderSignature As Long
  VersionNeededToExtract As Integer
  GeneralPurposeBitFlag As Integer
  CompressionMethod As Integer
  LastModFileTime As Integer
  LastModFileDate As Integer
  CRC32 As Long
  CompressedSize As Long
  UnCompressedSize As Long
  FileNameLength As Integer
  ExtraFieldLength As Integer
End Type
 
Private Const EndOFCentralDirSignature As Long = &H6054B50
Private Const CentralFileHeaderSigniature As Long = &H2014B50
Private Const LocalFileHeaderSignature As Long = &H4034B50
 
Private CentralFileHeader As typCentralFileHeader
Private CentralDirEnd As typCenteralDirEnd
 
Private CentralDirEndPos As Long
 
Public Event Progress(Percent As Long, Cancel As Boolean)
Public Event Status(Text As String)
Public Event ZipError(Number As eZipError, Description As String)
 
Public Property Get ZLibVersion() As String
  On Error GoTo errHandler
  
  ZLibVersion = PointerToString(ZLibVer)
  Exit Property
 
errHandler:
   RaiseEvent ZipError(zeZLibNotInstalled, "Zlib is not installed")
End Property
 
Public Function OpenZip(ZipPath As String) As Boolean
 
  m_bOpenZip = False
  
  RaiseEvent Status("Opening Zip")
  CloseZip
 
  If Not FileExists(ZipPath) Then
    RaiseEvent ZipError(zeFileNotFound, "The file " & ZipPath & " doesn't exist")
    Exit Function
  End If
 
  m_fID = FreeFile
  Open ZipPath For Binary As #m_fID
  
  CentralDirEndPos = GetCentralDirEndPos(m_fID)
  If CentralDirEndPos > 0 Then
    m_bOpenZip = True
    OpenZip = True
    RaiseEvent Status("Zip Opened")
  Else
    RaiseEvent ZipError(zeNotZipFile, "The file " & ZipPath & " is not a Zip file")
  End If
   
End Function
 
Public Sub CloseZip()
  If m_fID <> 0 Then
     Close #m_fID
     m_fID = 0
     RaiseEvent Status("Zip Closed")
  End If
  CentralDirEndPos = 0
  
End Sub
 
Public Property Get Files() As Collection
  Dim l As Long
  Dim sFilename As String
  
  Set Files = New Collection
  
  If m_bOpenZip Then
    If ReadCentralDirEnd(CentralDirEndPos) Then
      
      Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
      For l = 1 To CentralDirEnd.EntriesInTheCentralDir
        ReadCentralFileHeader sFilename
        Files.Add sFilename, sFilename
      Next l
    End If
  End If
  
End Property
 
Public Function GetFiles() As String()
  Dim l As Long
  Dim sFilename As String
  Dim aTemp() As String
  
  If m_bOpenZip Then
    If ReadCentralDirEnd(CentralDirEndPos) Then
      ReDim aTemp(CentralDirEnd.EntriesInTheCentralDir - 1)
      
      Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
      For l = 1 To CentralDirEnd.EntriesInTheCentralDir
        ReadCentralFileHeader sFilename
        aTemp(l - 1) = sFilename
      Next l
    End If
  End If
  
  GetFiles = aTemp
End Function
 
Public Function Count() As Long
  If m_bOpenZip Then
    Count = CentralDirEnd.EntriesInTheCentralDir
  Else
    Count = -1
  End If
End Function
 
'---------------------------------------------------------------------------------------
' Procedure : ExtractToMemory
' DateTime  : 18-11-2006
' Author    : ArnoutV
' Purpose   :
'---------------------------------------------------------------------------------------
Public Function ExtractToMemory(ByVal sExtractFile As String, bData() As Byte) As Boolean
  Dim l As Long
  Dim FilePos As Long
  Dim sFilename As String
   
  If Len(ZLibVersion) = 0 Then
     Exit Function
  End If
   
  If CentralDirEndPos = 0 Then
    RaiseEvent ZipError(zeNoOpenZipFile, "There is no Zip File Open")
    Exit Function
  End If
   
  sExtractFile = LCase$(sExtractFile)
  
  If ReadCentralDirEnd(CentralDirEndPos) Then
    Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
    
    For l = 1 To CentralDirEnd.EntriesInTheCentralDir
      ReadCentralFileHeader sFilename
      If LCase$(GetFileName(sFilename)) = sExtractFile Then
        If CentralFileHeader.UnCompressedSize > 0 Then
          FilePos = Seek(m_fID)
          ExtractToMemory = ExtractArray(sFilename, bData)
        End If
        Exit For
      End If
    Next l
  End If
 
End Function
 
Private Function GetFileName(Path As String) As String
  Dim l As Long
  
  l = InStrRev(Path, "\")
  If l > 0 Then GetFileName = Right$(Path, Len(Path) - l) Else GetFileName = Path
   
End Function
 
Private Function GetFilePath(Path As String) As String
 Dim l As Long
 
 l = InStrRev(Path, "\")
 If l > 0 Then GetFilePath = Left$(Path, l - 1)
   
End Function
 
Private Sub ReadCentralFileHeader(FileName As String)
  Dim ExtraField As String
  Dim Comment As String
  
  Get #m_fID, , CentralFileHeader
  If CentralFileHeader.CentralFileHeaderSigniature = CentralFileHeaderSigniature Then
    FileName = Space(CentralFileHeader.FileNameLength)
    Get #m_fID, , FileName
    FileName = Replace(FileName, "/", "\")
    ExtraField = Space(CentralFileHeader.ExtraFieldLength)
    Get #m_fID, , ExtraField
    Comment = Space(CentralFileHeader.FileCommentLength)
    Get #m_fID, , Comment
  End If
 
End Sub
 
Private Function ReadCentralDirEnd(Position As Long) As Boolean
  Dim ZipComment As String
  
  Get #m_fID, Position, CentralDirEnd
  ZipComment = Space(CentralDirEnd.ZipFileCommentLength)
  Get #m_fID, , ZipComment
  
  ReadCentralDirEnd = CentralDirEnd.NumberOfThisDisk = CentralDirEnd.NumberOfDiskWithCentralDir
End Function
 
'---------------------------------------------------------------------------------------
' Procedure : ExtractArray
' DateTime  : 18-11-2006
' Author    : ArnoutV
' Purpose   :
'---------------------------------------------------------------------------------------
Private Function ExtractArray(Path As String, b() As Byte) As Boolean
  Dim LocalFileHeader As typLocalFileHeader
  Dim sFilename As String
  Dim sExtraField As String
 
  Get #m_fID, CentralFileHeader.RelativeOffsetOfLocalHeader + 1, LocalFileHeader
  If LocalFileHeader.LocalFileHeaderSignature = LocalFileHeaderSignature Then
    sFilename = Space(LocalFileHeader.FileNameLength)
    Get #m_fID, , sFilename
    sExtraField = Space(LocalFileHeader.ExtraFieldLength)
    Get #m_fID, , sExtraField
    ReDim b(LocalFileHeader.CompressedSize - 1)
    Get #m_fID, , b
    If CentralFileHeader.CompressionMethod = 0 Then
      'No Compression
      ExtractArray = True
    ElseIf CentralFileHeader.CompressionMethod = 8 Then 'Deflate Method
      If UnCompressBytes(b, LocalFileHeader.CompressedSize, LocalFileHeader.UnCompressedSize, LocalFileHeader.CRC32) Then
        ExtractArray = True
      Else
        RaiseEvent ZipError(zeChecksumError, "Data checksum error in " & Path)
      End If
    Else
      RaiseEvent ZipError(zeUnsupportedCompressionMethod, "The compression Method for " & sFilename & " is unsupported")
    End If
  End If
   
End Function
 
Private Function GetCentralDirEndPos(fID As Integer) As Long
 
  Dim bData() As Byte
  Dim l As Long
  Dim m As Long
 
  ReDim bData(LOF(fID) - 1)
  Get #fID, , bData
  
  For l = UBound(bData) - 3 To LBound(bData) Step -1
    CopyMemory m, bData(l), 4
    If m = EndOFCentralDirSignature Then
      GetCentralDirEndPos = l + 1
      Exit Function
    End If
  Next
 
End Function
 
Private Function UnCompressBytes(Buffer() As Byte, CompressedSize As Long, UnCompressedSize As Long, CRC32 As Long) As Boolean
   
  Dim b() As Byte
 
  Dim BufferSize As Long
  Dim FileSize As Long
  
  Dim DecompressCRC32 As Long
  Dim r As Long
 
  ReDim b(UBound(Buffer) + 2)
  
  'Zlib's Uncompress method expects the 2 byte head that the Compress method adds
  'so we put that on first. Luckily it's always the same value.
  b(0) = 120
  b(1) = 156
  CopyMemory b(2), Buffer(0), UBound(Buffer) + 1
 
  FileSize = UBound(Buffer) + 3
  BufferSize = CentralFileHeader.UnCompressedSize * 1.01 + 12
  ReDim Buffer(BufferSize - 1) As Byte
  
  r = Uncompress(Buffer(0), BufferSize, b(0), FileSize)
 
  ReDim Preserve Buffer(CentralFileHeader.UnCompressedSize - 1)
  DecompressCRC32 = lCRC32(0&, Buffer(0), UBound(Buffer) + 1)
  If DecompressCRC32 = CRC32 Then
    UnCompressBytes = True
  End If
 
End Function
 
Private Function PointerToString(Pointer As Long) As String
  Dim l As Long
  Dim s As String
  
  l = lstrlen(Pointer)
  s = Space(l)
  l = lstrcpy(s, Pointer)
  If l > 0 Then
     PointerToString = s
  End If
  
End Function
 
Private Function FileExists(sSource As String) As Boolean
 
  Dim WFD As WIN32_FIND_DATA
  Dim hFile As Long
  
  hFile = FindFirstFile(sSource, WFD)
  FileExists = hFile <> INVALID_HANDLE_VALUE
  
  Call FindClose(hFile)
   
End Function
 
Private Sub Class_Terminate()
  CloseZip
End Sub
Миниатюры
Работа с zip архивами  
Вложения
Тип файла: zip zlibwapi class.zip (642.8 Кб, 4 просмотров)
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 23:20
Цитата Сообщение от testuser2 Посмотреть сообщение
zipOpen, zipOpenNewFileInZip и zipWriteInFileInZip
Чтение, думаю, должно быть таким: unzOpen, UnzOpenCurrentFile, unzReadCurrentFile
Знаешь я тоже так думаю что должно быть примерно так и я об этом тоже думал. Просто у нас нет такого кода который читает список файлов внутри зипа с помощью этой библиотеки. А класс который нам дали, там получается уже самописный код для чтения структуры ZIP - не используются функции DLL-библиотеки. По сути там только распаковка буфера используется из DLL.

Добавлено через 2 минуты
Это наталкивает меня на мысль, что если ещё немного доработать этот класс, то и распаковывать буфер можно самому вручную, без DLL, и при этом не использовать слишком большой громоздкий класс от гения-болгара wqweto.

Добавлено через 39 минут
testuser2, помнишь я тебе давал ссылку на распаковку ZIP-буфера вручную? https://github.com/lsimao/infl... te.bas#L30
Так вот используя этот код можно обойтись вообще без всяких там DLL

Добавлено через 1 минуту
Просто я случайно нашёл на гитхабе эту функцию:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'Returns decompressed buffer from Deflate compressed data
' - Buffer: compressed byte buffer
' - Position: buffer starting index (zero if not specified)
'             returns position after compressed data
Private Function Inflate(buffer() As Byte, Optional ByRef position As Long) As Byte()
    'Input/output buffer control
    Dim pBit As Long, oBuf() As Byte, oSize As Long, oByte As Long
    'Alphabets
    Dim hcLit(), hcDist(), hcCLen()
    'Alphabets upper bounds and counts
    Dim ubLen As Long, cLen As Long
    'Auxiliar variables
    Dim bFinal As Long, bType As Long, i As Long, lit As Long, dist As Long, length As Long, lens() As Integer
    
    pInit
    Do
        bFinal = pReadBits(buffer, position, pBit, 1)
        bType = pReadBits(buffer, position, pBit, 2)
        If bType = 0 Then
            'no compression
            'skip any remaining bits in current partially processed byte
            position = position - (pBit > 0)
            pBit = 0
            'read LEN
            length = buffer(position) + buffer(position + 1) * &H100&
            'check NLEN
            If (buffer(position + 2) + buffer(position + 3) * &H100& Xor &HFFFF&) <> length Then Err.Raise 57002, "Inflate", "Bad block data!"
            position = position + 4
            'Check input buffer
            If UBound(buffer) < position + length - 1 Then Err.Raise 57003, "Deflate.Inflate", "Not enough data!"
            If length Then 'Avoid unnecessary processing
                If oSize - oByte < length Then oSize = oByte + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize - 1)
                CopyMemory oBuf(oByte), buffer(position), length
                position = position + length
                oByte = oByte + length
            End If
        ElseIf bType = 3 Then
            Err.Raise 57001, "Deflate.Inflate", "Invalid block!"
        Else 'BType=1 or BType=2
            If bType = 1 Then
                'compressed with fixed Huffman codes
                hcLit = hcLitF
                hcDist = hcDistF
            ElseIf bType = 2 Then
                'compressed with dynamic Huffman codes
                cLen = pReadBits(buffer, position, pBit, 5) + 257 'count HLIT
                ubLen = pReadBits(buffer, position, pBit, 5) + cLen 'upper bound HLIT+HDIST
                length = pReadBits(buffer, position, pBit, 4) + 3 'upper bound HCLEN
                ReDim lens(0 To 18)
                For i = 0 To length
                    lens(hlCLen_map(i)) = pReadBits(buffer, position, pBit, 3)
                Next
                hcCLen = pHTBuild(lens, 18, 7)
                ReDim lens(0 To ubLen)
                length = 0
                i = 0
                Do While i <= ubLen
                    lit = pHTDecode(buffer, position, pBit, hcCLen)
                    If lit <= 15 Then
                        lens(i) = lit
                        If lens(i) > length Then length = lens(i)
                        i = i + 1
                    ElseIf lit = 16 Then
                        For i = i To i + pReadBits(buffer, position, pBit, 2) + 2
                            lens(i) = lens(i - 1)
                        Next
                    Else
                        i = i + pReadBits(buffer, position, pBit, 3 - 4 * (lit = 18)) + 3 - 8 * (lit = 18)
                    End If
                Loop
                hcLit = pHTBuild(lens, cLen - 1, length)
                hcDist = pHTBuild(lens, ubLen - cLen, length, cLen)
            End If
            Do
                lit = pHTDecode(buffer, position, pBit, hcLit)
                If lit < 256& Then
                    If oByte >= oSize Then oSize = oSize + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize)
                    oBuf(oByte) = lit
                    oByte = oByte + 1
                ElseIf lit > 256& Then
                    length = aLit_Add(lit)
                    If aLit_Bits(lit) Then length = length + pReadBits(buffer, position, pBit, aLit_Bits(lit))
                    dist = pHTDecode(buffer, position, pBit, hcDist)
                    If aDist_Bits(dist) Then
                        dist = aDist_Add(dist) + pReadBits(buffer, position, pBit, aDist_Bits(dist))
                    Else
                        dist = aDist_Add(dist)
                    End If
                    If oByte + length > oSize Then oSize = oSize + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize)
                    For oByte = oByte To oByte + length - 1
                        oBuf(oByte) = oBuf(oByte - dist)
                    Next
                End If
            Loop Until lit = 256&
        End If
    Loop Until bFinal
    position = position - (pBit > 0) 'Skip remaining bits
    If oByte Then ReDim Preserve oBuf(0 To oByte - 1) 'Trim output buffer
    Inflate = oBuf
End Function
Если её сейчас встроить в этот класс, то никакие DLL не будут нужны. Только проверку контрольной суммы я не знаю как сделать, но это можно уже и оставить в качестве домашнего задания...

Добавлено через 9 минут
Ладно, так и быть добавим ещё функцию подсчёта контрольной суммы CRC32:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'+++
Public Function CRC32(ByRef Data() As Byte) As Long
    Dim Remainder As Long
    Dim i As Long
    Dim j As Long
    
    If RunOnce = False Then 'Check if the table has already been generated.
        RunOnce = True
        For i = 0 To 255
            Remainder = i
            For j = 0 To 7
                If Remainder And 1 Then
                    Remainder = ShiftRight(Remainder) Xor &HEDB88320
                Else
                    Remainder = ShiftRight(Remainder)
                End If
            Next j
            Table(i) = Remainder
        Next i
        TableReady = True
    End If
    If TableReady = False Then Exit Function 'Check if table calculation has started, but not completed, on another thread.
    
    
    'Calculate CRC32 of data.
    CRC32 = &HFFFFFFFF
    For i = 0 To UBound(Data)
        CRC32 = ShiftRight8(CRC32) Xor Table((CRC32 And &HFF&) Xor Data(i))
    Next i
    CRC32 = Not CRC32
End Function
 
Private Function ShiftRight(ByVal Value As Long) As Long
    Dim TopBit As Boolean
    TopBit = Value And &H80000000
    ShiftRight = (Value And &H7FFFFFFF) \ 2
    If TopBit Then ShiftRight = ShiftRight Or &H40000000
End Function
 
Private Function ShiftRight8(ByVal Value As Long) As Long
    ShiftRight8 = ShiftRight(Value)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
End Function
'+++
Добавлено через 54 секунды
Есть вродебы и API такая для подсчёта CRC32 но я не помню как её вызывать и из какой стандартной библиотеки DLL винды.

Добавлено через 45 секунд
Поэтому пока самописная пусть будет, надеюсь она не сильно медленная (содрал с иностранного форума)
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 23:31
Всё, я по быстрому сделал новый класс теперь уже с полным отказом от DLL:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
Option Explicit
 
' Извините, я этот класс переделал на полный отказ от zlibwapi.dll использую только свой самописный код распаковки
' Накорябал этот код великий HackerVlad (посдирал код с разных мест и соединил воедино чтобы работало)
 
Private m_fID As Integer
Private m_bOpenZip As Boolean
 
 
Private Const INVALID_HANDLE_VALUE As Long = -1
Private Const OPEN_EXISTING  As Long = 3
Private Const FILE_SHARE_READ  As Long = &H1
Private Const FILE_SHARE_WRITE  As Long = &H2
Private Const GENERIC_WRITE  As Long = &H40000000
Private Const GENERIC_READ As Long = &H80000000
Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
Private Const MAX_PATH As Long = 260
 
 
Private Type FILETIME
  dwLowDateTime As Long
  dwHighDateTime As Long
End Type
 
'Private Type SYSTEMTIME
'  Year As Integer
'  Month As Integer
'  DayOfWeek As Integer
'  Day As Integer
'  Hour As Integer
'  Minute As Integer
'  Second As Integer
'  Milliseconds As Integer
'End Type
 
Private Type WIN32_FIND_DATA
   dwFileAttributes As Long
   ftCreationTime As FILETIME
   ftLastAccessTime As FILETIME
   ftLastWriteTime As FILETIME
   nFileSizeHigh As Long
   nFileSizeLow As Long
   dwReserved0 As Long
   dwReserved1 As Long
   cFileName As String * MAX_PATH
   cAlternate As String * 14
End Type
 
 
Private Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Dest As Any, src As Any, ByVal length As Long) As Long
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpBuffer As String, ByVal lpString As Long) As Long
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
 
'Private Declare Function ZLibVer Lib "zlibwapi.dll" Alias "zlibVersion" () As Long
'Private Declare Function Compress Lib "zlibwapi.dll" Alias "compress" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
'Private Declare Function Compress2 Lib "zlibwapi.dll" Alias "compress2" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long, ByVal Level As Long) As Long
'Private Declare Function Uncompress Lib "zlibwapi.dll" Alias "uncompress" (Dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
'Private Declare Function lCRC32 Lib "zlibwapi.dll" Alias "crc32" (ByVal crc As Long, buffer As Any, ByVal length As Long) As Long
 
Private Declare Function DosDateTimeToFileTime Lib "kernel32.dll" (ByVal wFatDate As Long, ByVal wFatTime As Long, lpFileTime As FILETIME) As Long
Private Declare Function LocalFileTimeToFileTime Lib "kernel32.dll" (lpLocalFileTime As FILETIME, lpFileTime As FILETIME) As Long
 
Private Declare Function SetFileTime Lib "kernel32" (ByVal hFile As Long, CreationTime As FILETIME, LastAccessTime As FILETIME, LastWriteTime As FILETIME) As Long
 
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
 
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
 
                 
Public Enum eZipError
  zeZLibNotInstalled = 1
  zeNotZipFile = 2
  zeNoOpenZipFile = 3
  zeUnsupportedCompressionMethod = 4
  zeChecksumError = 5
  zeFileNotFound = 10
  zeFileAlreadyExists = 11
  zeCantRemoveFile = 12
  zeCantCreateFolder = 13
  zeCantCreateFile = 14
End Enum
 
Private Type typCentralFileHeader
  CentralFileHeaderSigniature As Long
  VersionMadeBy As Integer
  VersionNeededToExtract As Integer
  GeneralPurposeBitFlag As Integer
  CompressionMethod As Integer
  LastModFileTime As Integer
  LastModFileDate As Integer
  CRC32 As Long
  CompressedSize As Long
  UnCompressedSize As Long
  FileNameLength As Integer
  ExtraFieldLength As Integer
  FileCommentLength As Integer
  DiskNumberStart As Integer
  InternalFileAttributes As Integer
  ExternalFileAttributes As Long
  RelativeOffsetOfLocalHeader As Long
End Type
 
Private Type typCenteralDirEnd
  EndOFCentralDirSignature As Long
  NumberOfThisDisk As Integer
  NumberOfDiskWithCentralDir As Integer
  EntriesInTheCentralDirThisOnDisk As Integer
  EntriesInTheCentralDir As Integer
  SizeOfCentralDir As Long
  OffSetOfCentralDir As Long
  ZipFileCommentLength As Integer
End Type
 
Private Type typLocalFileHeader
  LocalFileHeaderSignature As Long
  VersionNeededToExtract As Integer
  GeneralPurposeBitFlag As Integer
  CompressionMethod As Integer
  LastModFileTime As Integer
  LastModFileDate As Integer
  CRC32 As Long
  CompressedSize As Long
  UnCompressedSize As Long
  FileNameLength As Integer
  ExtraFieldLength As Integer
End Type
 
Private Const EndOFCentralDirSignature As Long = &H6054B50
Private Const CentralFileHeaderSigniature As Long = &H2014B50
Private Const LocalFileHeaderSignature As Long = &H4034B50
 
Private CentralFileHeader As typCentralFileHeader
Private CentralDirEnd As typCenteralDirEnd
 
Private CentralDirEndPos As Long
 
Public Event Progress(Percent As Long, Cancel As Boolean)
Public Event Status(Text As String)
Public Event ZipError(Number As eZipError, Description As String)
 
'---
Private hlCLen_map(0 To 18) As Long, aLit_Bits(257 To 285) As Long, aLit_Add(257 To 285) As Long, aDist_Bits(0 To 29) As Long, aDist_Add(0 To 29) As Long
Private zhZero(1 To 15) '((0), (0,0), (0,0,0,0), ...)
Private hcLitF, hcDistF
Private z1BitMask(0 To 30) As Long '(&H01, &H02, &H04, &H08, &H10, &H20, &H40, &H80, ...
Private zBitsMask(0 To 30) As Long '(&H01, &H03, &H07, &H0F, &H1F, &H3F, &H7F, &HFF, ...
Private Const BUFFER_GROW_SIZE = 1048576 '1MB
'---
'+++
Dim Table(255) As Long
Dim RunOnce As Boolean
Dim TableReady As Boolean
'+++
 
Public Property Get ZLibVersion() As String
  On Error GoTo errHandler
  
  'ZLibVersion = PointerToString(ZLibVer)
  Exit Property
 
errHandler:
   RaiseEvent ZipError(zeZLibNotInstalled, "Zlib is not installed")
End Property
 
Public Function OpenZip(ZipPath As String) As Boolean
 
  m_bOpenZip = False
  
  RaiseEvent Status("Opening Zip")
  CloseZip
 
  If Not FileExists(ZipPath) Then
    RaiseEvent ZipError(zeFileNotFound, "The file " & ZipPath & " doesn't exist")
    Exit Function
  End If
 
  m_fID = FreeFile
  Open ZipPath For Binary As #m_fID
  
  CentralDirEndPos = GetCentralDirEndPos(m_fID)
  If CentralDirEndPos > 0 Then
    m_bOpenZip = True
    OpenZip = True
    RaiseEvent Status("Zip Opened")
  Else
    RaiseEvent ZipError(zeNotZipFile, "The file " & ZipPath & " is not a Zip file")
  End If
   
End Function
 
Public Sub CloseZip()
  If m_fID <> 0 Then
     Close #m_fID
     m_fID = 0
     RaiseEvent Status("Zip Closed")
  End If
  CentralDirEndPos = 0
  
End Sub
 
Public Property Get Files() As Collection
  Dim l As Long
  Dim sFilename As String
  
  Set Files = New Collection
  
  If m_bOpenZip Then
    If ReadCentralDirEnd(CentralDirEndPos) Then
      
      Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
      For l = 1 To CentralDirEnd.EntriesInTheCentralDir
        ReadCentralFileHeader sFilename
        Files.Add sFilename, sFilename
      Next l
    End If
  End If
  
End Property
 
Public Function GetFiles() As String()
  Dim l As Long
  Dim sFilename As String
  Dim aTemp() As String
  
  If m_bOpenZip Then
    If ReadCentralDirEnd(CentralDirEndPos) Then
      ReDim aTemp(CentralDirEnd.EntriesInTheCentralDir - 1)
      
      Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
      For l = 1 To CentralDirEnd.EntriesInTheCentralDir
        ReadCentralFileHeader sFilename
        aTemp(l - 1) = sFilename
      Next l
    End If
  End If
  
  GetFiles = aTemp
End Function
 
Public Function Count() As Long
  If m_bOpenZip Then
    Count = CentralDirEnd.EntriesInTheCentralDir
  Else
    Count = -1
  End If
End Function
 
'---------------------------------------------------------------------------------------
' Procedure : ExtractToMemory
' DateTime  : 18-11-2006
' Author    : ArnoutV
' Purpose   :
'---------------------------------------------------------------------------------------
Public Function ExtractToMemory(ByVal sExtractFile As String, bData() As Byte) As Boolean
  Dim l As Long
  Dim FilePos As Long
  Dim sFilename As String
 
  'If Len(ZLibVersion) = 0 Then
  '   Exit Function
  'End If
  
  If CentralDirEndPos = 0 Then
    RaiseEvent ZipError(zeNoOpenZipFile, "There is no Zip File Open")
    Exit Function
  End If
 
  sExtractFile = LCase$(sExtractFile)
  
  If ReadCentralDirEnd(CentralDirEndPos) Then
    Seek #m_fID, CentralDirEnd.OffSetOfCentralDir + 1
    
    For l = 1 To CentralDirEnd.EntriesInTheCentralDir
      ReadCentralFileHeader sFilename
      If LCase$(GetFileName(sFilename)) = sExtractFile Then
        If CentralFileHeader.UnCompressedSize > 0 Then
          FilePos = Seek(m_fID)
          ExtractToMemory = ExtractArray(sFilename, bData)
        End If
        Exit For
      End If
    Next l
  End If
 
End Function
 
Private Function GetFileName(Path As String) As String
  Dim l As Long
  
  l = InStrRev(Path, "\")
  If l > 0 Then GetFileName = Right$(Path, Len(Path) - l) Else GetFileName = Path
   
End Function
 
Private Function GetFilePath(Path As String) As String
 Dim l As Long
 
 l = InStrRev(Path, "\")
 If l > 0 Then GetFilePath = Left$(Path, l - 1)
   
End Function
 
Private Sub ReadCentralFileHeader(FileName As String)
  Dim ExtraField As String
  Dim Comment As String
  
  Get #m_fID, , CentralFileHeader
  If CentralFileHeader.CentralFileHeaderSigniature = CentralFileHeaderSigniature Then
    FileName = Space(CentralFileHeader.FileNameLength)
    Get #m_fID, , FileName
    FileName = Replace(FileName, "/", "\")
    ExtraField = Space(CentralFileHeader.ExtraFieldLength)
    Get #m_fID, , ExtraField
    Comment = Space(CentralFileHeader.FileCommentLength)
    Get #m_fID, , Comment
  End If
 
End Sub
 
Private Function ReadCentralDirEnd(position As Long) As Boolean
  Dim ZipComment As String
  
  Get #m_fID, position, CentralDirEnd
  ZipComment = Space(CentralDirEnd.ZipFileCommentLength)
  Get #m_fID, , ZipComment
  
  ReadCentralDirEnd = CentralDirEnd.NumberOfThisDisk = CentralDirEnd.NumberOfDiskWithCentralDir
End Function
 
'---------------------------------------------------------------------------------------
' Procedure : ExtractArray
' DateTime  : 18-11-2006
' Author    : ArnoutV
' Purpose   :
'---------------------------------------------------------------------------------------
Private Function ExtractArray(Path As String, b() As Byte) As Boolean
  Dim LocalFileHeader As typLocalFileHeader
  Dim sFilename As String
  Dim sExtraField As String
 
  Get #m_fID, CentralFileHeader.RelativeOffsetOfLocalHeader + 1, LocalFileHeader
  If LocalFileHeader.LocalFileHeaderSignature = LocalFileHeaderSignature Then
    sFilename = Space(LocalFileHeader.FileNameLength)
    Get #m_fID, , sFilename
    sExtraField = Space(LocalFileHeader.ExtraFieldLength)
    Get #m_fID, , sExtraField
    ReDim b(LocalFileHeader.CompressedSize - 1)
    Get #m_fID, , b
    If CentralFileHeader.CompressionMethod = 0 Then
      'No Compression
      ExtractArray = True
    ElseIf CentralFileHeader.CompressionMethod = 8 Then 'Deflate Method
      If UnCompressBytes(b, LocalFileHeader.CompressedSize, LocalFileHeader.UnCompressedSize, LocalFileHeader.CRC32) Then
        ExtractArray = True
      Else
        RaiseEvent ZipError(zeChecksumError, "Data checksum error in " & Path)
      End If
    Else
      RaiseEvent ZipError(zeUnsupportedCompressionMethod, "The compression Method for " & sFilename & " is unsupported")
    End If
  End If
   
End Function
 
Private Function GetCentralDirEndPos(fID As Integer) As Long
 
  Dim bData() As Byte
  Dim l As Long
  Dim m As Long
 
  ReDim bData(LOF(fID) - 1)
  Get #fID, , bData
  
  For l = UBound(bData) - 3 To LBound(bData) Step -1
    CopyMemory m, bData(l), 4
    If m = EndOFCentralDirSignature Then
      GetCentralDirEndPos = l + 1
      Exit Function
    End If
  Next
 
End Function
 
'---
Private Function pHTDecode(buffer, pByte As Long, pBit As Long, htCodes) As Integer
    Dim code As Long, l As Long
    For l = 1 To 15 'Max len possible
        code = code * 2 - ((buffer(pByte) And z1BitMask(pBit)) <> 0)
        pBit = (pBit + 1) And 7
        If pBit = 0 Then pByte = pByte + 1
        If htCodes(l)(code) Then pHTDecode = htCodes(l)(code) - 1: Exit Function
    Next
    Err.Raise 57004, "Deflate.Inflate", "Invalid data!"
End Function
 
Private Function pHTBuild(htLen, ByVal max_code As Long, ByVal max_len As Long, Optional ByVal Index As Long)
    Dim htCode(), bl_count(0 To 15) As Long, code As Long, next_code(0 To 15) As Long, i As Long
    For i = 0 To max_code
        bl_count(htLen(i + Index)) = bl_count(htLen(i + Index)) + 1
    Next
    bl_count(0) = 0
    For i = 1 To max_len
        code = (code + bl_count(i - 1)) * 2
        next_code(i) = code
    Next
    htCode = zhZero
    For i = 0 To max_code
        If htLen(i + Index) Then
            htCode(htLen(i + Index))(next_code(htLen(i + Index))) = i + 1
            next_code(htLen(i + Index)) = next_code(htLen(i + Index)) + 1
        End If
    Next
    pHTBuild = htCode
End Function
 
'Max bits read at once: 13 (Dist extra bits). Huffman decoding uses inline reading!
Private Function pReadBits(buffer, pByte As Long, pBit As Long, ByVal Size As Long) As Long
    Dim ret As Long
    'Read first byte:
    ret = buffer(pByte) \ z1BitMask(pBit)
    pBit = pBit + Size
    If pBit < 8 Then pReadBits = ret And zBitsMask(Size): Exit Function
    'Not enough, read second byte:
    Dim bw As Long 'bits written
    bw = 8 - pBit + Size
    pBit = Size - bw
    ret = (zBitsMask(pBit) And buffer(pByte + 1)) * z1BitMask(bw) + ret
    If pBit < 8 Then pByte = pByte + 1: pReadBits = ret: Exit Function
    'Not enough, read third and last byte:
    bw = bw + 8
    pBit = pBit - 8
    pByte = pByte + 2
    pReadBits = (zBitsMask(pBit) And buffer(pByte)) * z1BitMask(bw) + ret
End Function
 
Private Sub pInit()
    Dim i As Long, a_b() As String, a_a() As String, a16() As Integer
    If hlCLen_map(0) = 16 Then Exit Sub 'Still init'd
    
    'Tables:
    'Literal/Length alphabet extra bits
    a_b = Split("0 0 0 0 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 0")
    a_a = Split("3 4 5 6 7 8 9 10 11 13 15 17 19 23 27 31 35 43 51 59 67 83 99 115 131 163 195 227 258")
    For i = 257 To 285
        aLit_Bits(i) = a_b(i - 257)
        aLit_Add(i) = a_a(i - 257)
    Next
    'Distance alphabet extra bits
    a_b = Split("0 0 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13")
    a_a = Split("1 2 3 4 5 7 9 13 17 25 33 49 65 97 129 193 257 385 513 769 1025 1537 2049 3073 4097 6145 8193 12289 16385 24577")
    For i = 0 To 29
        aDist_Bits(i) = a_b(i)
        aDist_Add(i) = a_a(i)
    Next
    'Code length read order
    a_a = Split("16 17 18 0 8 7 9 6 10 5 11 4 12 3 13 2 14 1 15")
    For i = 0 To 18
        hlCLen_map(i) = a_a(i)
    Next
    
    'Empty Huffman tree
    For i = 1 To 15
        ReDim a16(0 To 2 ^ i - 1)
        zhZero(i) = a16
    Next
    
    'Static Huffman tree
    hcLitF = zhZero
    hcDistF = zhZero
    For i = 0 To 143: hcLitF(8)(48 + i) = i + 1: Next
    For i = 144 To 255: hcLitF(9)(400 + i - 144) = i + 1: Next
    For i = 256 To 279: hcLitF(7)(i - 256) = i + 1: Next
    For i = 280 To 287: hcLitF(8)(192 + i - 280) = i + 1: Next
    For i = 0 To 29: hcDistF(5)(i) = i + 1: Next
    
    'Bit masks
    For i = 0 To 30
        z1BitMask(i) = 2 ^ i
        zBitsMask(i) = 2 ^ i - 1
    Next
 
End Sub
 
'Returns decompressed buffer from Deflate compressed data
' - Buffer: compressed byte buffer
' - Position: buffer starting index (zero if not specified)
'             returns position after compressed data
Private Function Inflate(buffer() As Byte, Optional ByRef position As Long) As Byte()
    'Input/output buffer control
    Dim pBit As Long, oBuf() As Byte, oSize As Long, oByte As Long
    'Alphabets
    Dim hcLit(), hcDist(), hcCLen()
    'Alphabets upper bounds and counts
    Dim ubLen As Long, cLen As Long
    'Auxiliar variables
    Dim bFinal As Long, bType As Long, i As Long, lit As Long, dist As Long, length As Long, lens() As Integer
    
    pInit
    Do
        bFinal = pReadBits(buffer, position, pBit, 1)
        bType = pReadBits(buffer, position, pBit, 2)
        If bType = 0 Then
            'no compression
            'skip any remaining bits in current partially processed byte
            position = position - (pBit > 0)
            pBit = 0
            'read LEN
            length = buffer(position) + buffer(position + 1) * &H100&
            'check NLEN
            If (buffer(position + 2) + buffer(position + 3) * &H100& Xor &HFFFF&) <> length Then Err.Raise 57002, "Inflate", "Bad block data!"
            position = position + 4
            'Check input buffer
            If UBound(buffer) < position + length - 1 Then Err.Raise 57003, "Deflate.Inflate", "Not enough data!"
            If length Then 'Avoid unnecessary processing
                If oSize - oByte < length Then oSize = oByte + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize - 1)
                CopyMemory oBuf(oByte), buffer(position), length
                position = position + length
                oByte = oByte + length
            End If
        ElseIf bType = 3 Then
            Err.Raise 57001, "Deflate.Inflate", "Invalid block!"
        Else 'BType=1 or BType=2
            If bType = 1 Then
                'compressed with fixed Huffman codes
                hcLit = hcLitF
                hcDist = hcDistF
            ElseIf bType = 2 Then
                'compressed with dynamic Huffman codes
                cLen = pReadBits(buffer, position, pBit, 5) + 257 'count HLIT
                ubLen = pReadBits(buffer, position, pBit, 5) + cLen 'upper bound HLIT+HDIST
                length = pReadBits(buffer, position, pBit, 4) + 3 'upper bound HCLEN
                ReDim lens(0 To 18)
                For i = 0 To length
                    lens(hlCLen_map(i)) = pReadBits(buffer, position, pBit, 3)
                Next
                hcCLen = pHTBuild(lens, 18, 7)
                ReDim lens(0 To ubLen)
                length = 0
                i = 0
                Do While i <= ubLen
                    lit = pHTDecode(buffer, position, pBit, hcCLen)
                    If lit <= 15 Then
                        lens(i) = lit
                        If lens(i) > length Then length = lens(i)
                        i = i + 1
                    ElseIf lit = 16 Then
                        For i = i To i + pReadBits(buffer, position, pBit, 2) + 2
                            lens(i) = lens(i - 1)
                        Next
                    Else
                        i = i + pReadBits(buffer, position, pBit, 3 - 4 * (lit = 18)) + 3 - 8 * (lit = 18)
                    End If
                Loop
                hcLit = pHTBuild(lens, cLen - 1, length)
                hcDist = pHTBuild(lens, ubLen - cLen, length, cLen)
            End If
            Do
                lit = pHTDecode(buffer, position, pBit, hcLit)
                If lit < 256& Then
                    If oByte >= oSize Then oSize = oSize + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize)
                    oBuf(oByte) = lit
                    oByte = oByte + 1
                ElseIf lit > 256& Then
                    length = aLit_Add(lit)
                    If aLit_Bits(lit) Then length = length + pReadBits(buffer, position, pBit, aLit_Bits(lit))
                    dist = pHTDecode(buffer, position, pBit, hcDist)
                    If aDist_Bits(dist) Then
                        dist = aDist_Add(dist) + pReadBits(buffer, position, pBit, aDist_Bits(dist))
                    Else
                        dist = aDist_Add(dist)
                    End If
                    If oByte + length > oSize Then oSize = oSize + BUFFER_GROW_SIZE: ReDim Preserve oBuf(0 To oSize)
                    For oByte = oByte To oByte + length - 1
                        oBuf(oByte) = oBuf(oByte - dist)
                    Next
                End If
            Loop Until lit = 256&
        End If
    Loop Until bFinal
    position = position - (pBit > 0) 'Skip remaining bits
    If oByte Then ReDim Preserve oBuf(0 To oByte - 1) 'Trim output buffer
    Inflate = oBuf
End Function
'---
 
'+++
Public Function CRC32(ByRef Data() As Byte) As Long
    Dim Remainder As Long
    Dim i As Long
    Dim j As Long
    
    If RunOnce = False Then 'Check if the table has already been generated.
        RunOnce = True
        For i = 0 To 255
            Remainder = i
            For j = 0 To 7
                If Remainder And 1 Then
                    Remainder = ShiftRight(Remainder) Xor &HEDB88320
                Else
                    Remainder = ShiftRight(Remainder)
                End If
            Next j
            Table(i) = Remainder
        Next i
        TableReady = True
    End If
    If TableReady = False Then Exit Function 'Check if table calculation has started, but not completed, on another thread.
    
    
    'Calculate CRC32 of data.
    CRC32 = &HFFFFFFFF
    For i = 0 To UBound(Data)
        CRC32 = ShiftRight8(CRC32) Xor Table((CRC32 And &HFF&) Xor Data(i))
    Next i
    CRC32 = Not CRC32
End Function
 
Private Function ShiftRight(ByVal Value As Long) As Long
    Dim TopBit As Boolean
    TopBit = Value And &H80000000
    ShiftRight = (Value And &H7FFFFFFF) \ 2
    If TopBit Then ShiftRight = ShiftRight Or &H40000000
End Function
 
Private Function ShiftRight8(ByVal Value As Long) As Long
    ShiftRight8 = ShiftRight(Value)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
    ShiftRight8 = ShiftRight(ShiftRight8)
End Function
'+++
 
Private Function UnCompressBytes(buffer() As Byte, CompressedSize As Long, UnCompressedSize As Long, getCRC32 As Long) As Boolean
   
  Dim b() As Byte
  Dim b2() As Byte
 
  Dim BufferSize As Long
  Dim FileSize As Long
  
  Dim DecompressCRC32 As Long
  Dim r As Long
 
 
 
  ReDim b(UBound(buffer) + 2)
  
  'Zlib's Uncompress method expects the 2 byte head that the Compress method adds
  'so we put that on first. Luckily it's always the same value.
  b(0) = 120
  b(1) = 156
  CopyMemory b(2), buffer(0), UBound(buffer) + 1
 
  FileSize = UBound(buffer) + 3
  BufferSize = CentralFileHeader.UnCompressedSize * 1.01 + 12
  'ReDim buffer(BufferSize - 1) As Byte
  
   
  'r = Uncompress(buffer(0), BufferSize, b(0), FileSize)
  
  b2 = Inflate(buffer)
  buffer = b2
    
  ReDim Preserve buffer(CentralFileHeader.UnCompressedSize - 1)
  
  'DecompressCRC32 = lCRC32(0&, buffer(0), UBound(buffer) + 1)
  DecompressCRC32 = CRC32(buffer)
  
  If DecompressCRC32 = getCRC32 Then
    UnCompressBytes = True
  End If
 
End Function
 
Private Function PointerToString(Pointer As Long) As String
  Dim l As Long
  Dim s As String
  
  l = lstrlen(Pointer)
  s = Space(l)
  l = lstrcpy(s, Pointer)
  If l > 0 Then
     PointerToString = s
  End If
  
End Function
 
Private Function FileExists(sSource As String) As Boolean
 
  Dim WFD As WIN32_FIND_DATA
  Dim hFile As Long
  
  hFile = FindFirstFile(sSource, WFD)
  FileExists = hFile <> INVALID_HANDLE_VALUE
  
  Call FindClose(hFile)
   
End Function
 
Private Sub Class_Terminate()
  CloseZip
End Sub
Хочу только отметить что через DLL распаковка идёт всё же быстрее. А этот код распаковки слегка чуть медленнее.

Код формы:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Option Explicit
Dim zip As New clsZipExtractionClass
Private Declare Function SafeArrayGetDim Lib "oleaut32.dll" (arr() As Any) As Long
 
Private Sub Command1_Click()
    Dim strArray() As String
    Dim i As Long
    
    zip.OpenZip App.Path & "\test.zip"
    
    strArray() = zip.GetFiles ' Get a list files inside a ZIP
    
    If SafeArrayGetDim(strArray) > 0 Then
        For i = 0 To UBound(strArray)
            List1.AddItem strArray(i)
        Next
        
        List1.Selected(0) = True
        Label1.Caption = "Count files: " & zip.Count
        List1.SetFocus
    End If
    
    zip.CloseZip
End Sub
 
Private Sub List1_Click()
    Dim bytesData() As Byte
    
    zip.OpenZip App.Path & "\test.zip"
    zip.ExtractToMemory List1.Text, bytesData
    zip.CloseZip
    
    If SafeArrayGetDim(bytesData) > 0 Then Picture1.Picture = PictureFromBits(bytesData)
End Sub
Миниатюры
Работа с zip архивами  
Вложения
Тип файла: zip zlibwapi class.zip (609.1 Кб, 9 просмотров)
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
29.10.2024, 23:34
Зато этот новый класс весит всего 24 Кб! И поэтому EXE-файл будет не таким большим.
И реализовано абсолютно всё о чём только мечтал testuser2. А именно распаковка любых файлов, на выбор, из ZIP-архива напрямую в байтовый массив, а не в файл.
0
Модератор
10057 / 3902 / 884
Регистрация: 22.02.2013
Сообщений: 5,853
Записей в блоге: 79
29.10.2024, 23:41
https://www.cyberforum.ru/post6183877.html
Без внешних зависимостей.
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 01:19
The trick, ок, ты там написал "Позже сделаю класс для работы с архивами непосредственно работающий с Zipfldr.dll" ты сделал класс? наверное нет, да и там тот код я не понял там только Form_Load и мало кода у тебя и всё.

Добавлено через 52 секунды
The trick, у тебя там через shell32 извлекает или как я не понял.

Добавлено через 28 минут
The trick, ты случайно не помнишь API для подсчёта CRC32? А то мне кажется что самописная медленно работает.

Добавлено через 11 минут
Цитата Сообщение от The trick Посмотреть сообщение
Без внешних зависимостей
А zipfldr.dll есть в XP или в Win2000 например?

Добавлено через 38 секунд
Это не нативная библиотека а ActiveX или COM'авскоя...

Добавлено через 22 минуты
Кажется нашёл:

Visual Basic
1
2
3
4
5
6
7
8
Private Declare Function RtlComputeCrc32 Lib "ntdll.dll" ( _
     ByVal dwInitial As Long, _
     ByVal pData As Long, _
     ByVal iLen As Long) As Long
 
Public Function Crc32Api ( tBuff() As Byte) as long    
    Crc32Api = RtlComputeCrc32(0, VarPtr(tBuff(0)), UBound(tBuff) + 1)
End Function
Это должно быть гораздо быстрее, я думаю, надо будет попробовать!

Добавлено через 29 минут
Я сравнил два своих проекта по скоростям, который использует DLL для распаковки, и который не использует... Разница в скорости конечно очень существенная. Самописный скрипт распаковки для 600 Кб файла 400 млск времени занимает, а из DLL почти мгновенно всего за 16 млск.
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 01:25
Сами смотрите что получилось по скоростям, всего для 400Кб файла при распаковке...
Миниатюры
Работа с zip архивами   Работа с zip архивами  
Вложения
Тип файла: zip zlibwapi class NO DLL.zip (608.9 Кб, 5 просмотров)
Тип файла: zip zlibwapi class DLL.zip (643.1 Кб, 5 просмотров)
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 01:42
Делаю для себя вывод, что найденная мною на просторах сети функция Inflate написанная на VB6 самописным кодом довольно медленная по сравнению с аналогичной функцией в DLL для распаковки буфера ZIP. Возможно у гения-болгара функция распаковки буфера будет по быстрее конечно, но лень уже ковыряться и вникать. Итак много сделал очень.

Добавлено через 1 минуту
Было бы неплохо распаковывать буфер с помощью библиотеки zipfldr.dll по технологии от The Trick тогда и скорость будет большая и никакие DLL с собой тягать не надо будет в виде zlibwapi.dll.

Добавлено через 12 минут
Вот начал разбираться с кодом от The Trick и сразже первый залипон не найдено описание структуры UUID. Надо думать почему.
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 01:44
У меня поэтому сразу же вопрос к товарищу трюкачу, как так вы даёте код, а он не работает и требует что-то не описанное вами...
Миниатюры
Работа с zip архивами  
0
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 01:56
И что такое As IShellExtInit что такое As IPersistFolder2
Мне надо что-то подключать в Reference какую-то TLB описывающею?

Добавлено через 23 секунды
Код есть а как с ним работать не понятно...

Добавлено через 6 минут
The trick, почему сразу нельзя было написать какие ещё нужны зависимости? почему я долен ломать голову где взять описание не описанных структур и целый час мучиться и так не запустить твой код ну

Добавлено через 1 минуту
The trick, и можно ли вообще с помощью zipfldr.dll распаковывать буфер? чисто буфер и всё?
0
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
30.10.2024, 13:44  [ТС]
Самый простой способ заюзать zipfldr.dll (только разархивация). С одного из форумов
С разархивацией все ОК: rundll32.exe zipfldr.dll,RouteTheCall %filename%.

Только архивацию пока сделать никак не получается.
Не хватает флажков, а документацию Microsoft не открывает...
Добавлено через 5 часов 35 минут
Распаковка в стиле Minizip, от того же волшебного чувака (dilettante).. https://www.vbforums.com/showt... ost5424767

Добавлено через 12 минут
Точнее там не распаковка, но получение информации

Добавлено через 14 минут
Пример на Vba с использованием Compression API
https://newbe.dev/vb-excel-vba... de-example
Эти функции вроде поддерживают формат MSZIP
1
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
30.10.2024, 17:03  [ТС]
Да свершится! Наконец-то я хоть что-то сделал сам в этой теме. Добавил распаковку в проект dilettante
Вложения
Тип файла: zip MiniZip demo.zip (100.7 Кб, 5 просмотров)
1
Испарился
 Аватар для HackerVlad
1741 / 637 / 45
Регистрация: 10.09.2021
Сообщений: 2,769
30.10.2024, 17:49
testuser2, так CAB-архив это совсем не ZIP

Добавлено через 2 минуты
testuser2, ты наконец-то нашёл способ как получить список файлов внутри зипа с помощью zlibwapi ?

Добавлено через 5 минут
testuser2, хочешь прикол? сам wqweto мне сказал что у него код распаковки медленнее чем если использовать DLL сам честно признался...

Добавлено через 1 минуту
То есть использую библиотеку zlibwapi.dll мы значительно выигрываем в скорости, как ни крути, особенно при больших объёмах это будет ощутимо-заметно...

Добавлено через 4 минуты
Цитата Сообщение от testuser2 Посмотреть сообщение
Наконец-то я хоть что-то сделал сам в этой теме
Пхахахах рассмешил ахахахха

Добавлено через 3 минуты
Цитата Сообщение от testuser2 Посмотреть сообщение
Добавил распаковку в проект dilettante
Что-то я этого не заметил, хотя скачал твой проект. Не вижу ничего чтобы ты сделал распаковку в буфер или на диск.

Добавлено через 2 минуты
testuser2, из формы ты даже не вызываешь свой накорябанный код GetCurrentFileInfo
0
1387 / 843 / 92
Регистрация: 08.02.2017
Сообщений: 3,593
Записей в блоге: 1
30.10.2024, 17:49  [ТС]
HackerVlad, примеров много, вот неплохой пример. Вроде бы это C, потому, что на С++ всякие квадратные скобки всфкая такая х..ня <<>>> ни че не понятно
Здесь структуры минизиповские можно посмотреть. Кстати лучше спользовать 64 версии функций. Перевод:
MiniZip предоставляет два набора открытых функций, но мы будем использовать только те, которые заканчиваются на 64. Остальные версии являются устаревшими и не должны использоваться. 64 указывают на поддержку 64-битного zip, который используется сегодня. Не волнуйтесь, потому что zipOpen64 и unzOpen64 по-прежнему могут открывать 32-битные zip-файлы.
Ист.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
30.10.2024, 17:49
Помогаю со студенческими работами здесь

access и zip архив
Привет всем! Подскажите... если есть возможность сохранение файла в zip архив Dim FileHeder As String Dim filePath As String ...

Как распаковать ZIP-файл в 7z?
'При помощи VBA WinRAR распаковывает архив в папку … q = Адрес_сохранения_файла 'путь к каталогу, то есть к папке, в конце пути для...

ребята!завтра надо сдать работу,а без этих работ никак((
алгоритмы линейной структуры 1) СОСТАВИТЬ ПРОГРАММУ ВЫЧИСЛЕНИЯ СРЕДНЕГО ЗНАЧЕНИЯ ТРЕХ ВЕЛИЧИН 2) ПОДСЧИТАТЬ И ВЫВЕСТИ НА ЭКРАН СУММУ И...

Замена файла в zip архиве при совпадении имени
Есть несколько excel файлов. например, 1.xls, 2.xls, 3.xls Есть куча zip архивов. например, A (1.xls), B (1.xls,5.doc,3.doc), C (3.xls),...

Как сделать архив zip?
Как сделать архив zip? Какие нужны библиотеки и где их взять? заранее спасибо.


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru