Сжатие ZipArchive не будет компилироваться

#vb.net #compression #.net-4.5 #ziparchive

#vb.net #сжатие #.net-4.5 #архив ziparchive

Вопрос:

У меня есть класс, который я преобразовал из C # в VB.NET (Структура 4.5)

Я пытаюсь использовать новые функции сжатия. Я думаю, что я выполнил ВСЕ инструкции из MSDN, но он все еще не компилируется.

ZipFile, ZipArchive и ZipArchiveEntry отображаются как «Тип не определен»

Я импортировал пространство имен «System», «System.Ввод-вывод» и «System.IO.Compression» в ссылках

Что еще мне нужно сделать, чтобы заставить это работать?

 Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Collections.Generic
Imports System.Linq

Public Class clsZip1
    ' Used to specify what our overwrite policy is for files we are extracting.
    Public Enum Overwrite
        Always = 0
        IfNewer = 1
        Never = -1
    End Enum

    ' Used to identify what we will do if we are trying to create a zip file and it already exists.
    Public Enum ArchiveAction
        eMerge = 0
        eReplace = 1
        eError = 2
        eIgnore = 3
    End Enum

    ' Unzips the specified file to the given folder in a safe manner.  
    ' This plans for missing paths and existing files and handles them gracefully.
    Public Sub ExtractToDirectory(ByVal sourceArchiveFileName As String,
                                  ByVal destinationDirectoryName As String,
                                  Optional ByVal overwriteMethod As Overwrite = Overwrite.IfNewer)
        'Opens the zip file up to be read
        Using archive As ZipArchive = ZipFile.OpenRead(sourceArchiveFileName)
            'Loops through each file in the zip file
            For Each file As ZipArchiveEntry In archive.Entries
                ImprovedExtractToFile(file, destinationDirectoryName, overwriteMethod)
            Next
        End Using
    End Sub

    ' Safely extracts a single file from a zip file
    Public Sub ExtractToFile(ByVal file As ZipArchiveEntry,
                             ByVal destinationPath As String,
                             Optional ByVal overwriteMethod As Overwrite = Overwrite.IfNewer)
        'Gets the complete path for the destination file, including any
        'relative paths that were in the zip file
        Dim destinationFileName As String = Path.Combine(destinationPath, file.FullName)

        'Gets just the new path, minus the file name so we can create the
        'directory if it does not exist
        Dim destinationFilePath As String = Path.GetDirectoryName(destinationFileName)

        'Creates the directory (if it doesn't exist) for the new path
        Directory.CreateDirectory(destinationFilePath)

        'Determines what to do with the file based upon the
        'method of overwriting chosen
        Select Case overwriteMethod
            Case Overwrite.Always
                'Just put the file in and overwrite anything that is found
                file.ExtractToFile(destinationFileName, True)
            Case Overwrite.IfNewer
                'Checks to see if the file exists, and if so, if it should
                'be overwritten
                If (Not file.Exists(destinationFileName) Or file.GetLastWriteTime(destinationFileName) < file.LastWriteTime) Then
                    'Either the file didn't exist or this file is newer, so
                    'we will extract it and overwrite any existing file
                    file.ExtractToFile(destinationFileName, True)
                End If
            Case Overwrite.Never
                'Put the file in if it is new but ignores the 
                'file if it already exists
                If (Not file.Exists(destinationFileName)) Then
                    file.ExtractToFile(destinationFileName)
                End If
        End Select
    End Sub

    ' Allows you to add files to an archive, whether the archive already exists or not
    Public Sub AddToArchive(ByVal archiveFullName As String,
                                    ByVal files As List(Of String),
                                    Optional ByVal action As ArchiveAction = ArchiveAction.eReplace,
                                    Optional ByVal fileOverwrite As Overwrite = Overwrite.IfNewer,
                                    Optional ByVal compression As CompressionLevel = CompressionLevel.Optimal)
        'Identifies the mode we will be using - the default is Create
        Dim mode As ZipArchiveMode = ZipArchiveMode.Create

        'Determines if the zip file even exists
        Dim archiveExists As Boolean = File.Exists(archiveFullName)

        'Figures out what to do based upon our specified overwrite method
        Select Case action
            Case ArchiveAction.eMerge
                'Sets the mode to update if the file exists, otherwise
                'the default of Create is fine
                If (archiveExists) Then mode = ZipArchiveMode.Update
            Case ArchiveAction.eReplace
                'Deletes the file if it exists.  Either way, the default
                'mode of Create is fine
                If (archiveExists) Then File.Delete(archiveFullName)
            Case ArchiveAction.eError
                'Throws an error if the file exists
                If (archiveExists) Then Throw New IOException(String.Format("The zip file {0} already exists.", archiveFullName))
            Case ArchiveAction.eIgnore
                'Closes the method silently and does nothing
                If (archiveExists) Then Return
            Case Else
        End Select

        'Opens the zip file in the mode we specified
        Using zipFile As ZipArchive = zipFile.Open(archiveFullName, mode)
            'This is a bit of a hack and should be refactored - I am
            'doing a similar foreach loop for both modes, but for Create
            'I am doing very little work while Update gets a lot of
            'code.  This also does not handle any other mode (of
            'which there currently wouldn't be one since we don't
            'use Read here).
            If (mode = ZipArchiveMode.Create) Then
                For Each file As String In files
                    'Adds the file to the archive
                    zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression)
                Next
            Else
                For Each file As String In files
                    Dim fileInZip = (From f In zipFile.Entries
                                     Where f.Name = Path.GetFileName(file)
                                     Select f).FirstOrDefault()

                    Select Case fileOverwrite
                        Case Overwrite.Always
                            'Deletes the file if it is found
                            If (fileInZip IsNot Nothing) Then
                                fileInZip.Delete()
                            End If
                            'Adds the file to the archive
                            zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression)
                        Case Overwrite.IfNewer
                            'This is a bit trickier - we only delete the file if it is
                            'newer, but if it is newer or if the file isn't already in
                            'the zip file, we will write it to the zip file
                            If (fileInZip IsNot Nothing) Then
                                'Deletes the file only if it is older than our file.
                                'Note that the file will be ignored if the existing file
                                'in the archive is newer.
                                If (fileInZip.LastWriteTime < file.GetLastWriteTime(file)) Then
                                    fileInZip.Delete()

                                    'Adds the file to the archive
                                    zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression)
                                Else
                                    'The file wasn't already in the zip file so add it to the archive
                                    zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression)
                                End If
                            End If
                        Case Overwrite.Never
                            'Don't do anything - this is a decision that you need to
                            'consider, however, since this will mean that no file will
                            'be writte.  You could write a second copy to the zip with
                            'the same name (not sure that is wise, however).
                        Case Else
                    End Select
                Next
            End If
        End Using
    End Sub
End Class
 

Ответ №1:

Вам нужно добавить ссылку на System.IO.Compression.dll . У меня работает только VS2010, поэтому я не могу это протестировать, но я предполагаю, что он доступен только для Framework 4.5, поскольку его нет на этом компьютере.

Откройте «Мой проект», перейдите на вкладку «Ссылки», щелкните раскрывающийся список «Добавить …» и выберите «Ссылка». В диалоговом окне добавления ссылки используйте .ЧИСТЫЙ тег, отсортируйте список по имени компонента и найдите System.IO.Compression.

Если его там нет, попробуйте поискать dll на жестком диске и используйте тот же диалог ссылок, чтобы добавить его вручную. Надеюсь, кто-то, у кого есть опыт работы с этой конкретной библиотекой, может прояснить любые отклонения в ее использовании.

Комментарии:

1. Да, это очень важная вещь. System.IO.Сжатие. dll уже добавлена в качестве ссылки.

2. Хорошо, следующий шаг — добавить ссылку на System.IO.Compression . Файловая система, которая добавляет ZipFile класс. Однако все еще есть проблемы с ExtractToFile процедурой; вам нужно переименовать первый параметр ( file ) , потому что он конфликтует с System.IO.File .

3. Аналогично, в AddToArchive подпрограмме Using... оператор создает переменную с тем же именем, что и у одного из классов в библиотеке. Немного тщательного переименования все уладит.