Используя SharpZipLib для разархивации определенных файлов?

Кроме того, Swiss Mister post, в моем случае window.open был запущен внутри обещания, который включил блокировку всплывающих окон, мое решение было: в угловом:

$scope.gotClick = function(){

  var myNewTab = browserService.openNewTab();
  someService.getUrl().then(
    function(res){
        browserService.updateLocation(res.url, myNewTab);

    }
  );
};

browserService:

this.openNewTab = function(){
     var newTabWindow = $window.open();
     return newTabWindow;
}

this.updateTabLocation = function(tabLocation, tab) {
     if(!tabLocation){
       tab.close();
     }
     tab.location.href = tabLocation;
}

так вы можете открыть новую вкладку с помощью ответа на обещание и не вызвать блокировщик всплывающих окон.

34
задан FlySwat 30 November 2008 в 02:05
поделиться

4 ответа

ZipFile. GetEntry должен добиться цели:

using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
using (var zf = new ZipFile(fs)) {
   var ze = zf.GetEntry(fileName);
   if (ze == null) {
      throw new ArgumentException(fileName, "not found in Zip");
   }

   using (var s = zf.GetInputStream(ze)) {
      // do something with ZipInputStream
   }
}
44
ответ дан 27 November 2019 в 16:39
поделиться
FastZip.ExtractZip (string zipFileName, string targetDirectory, string fileFilter)

может извлечь один или несколько файлов на основе фильтра файла (т.е. обычная строка expressoin)

Вот документ относительно фильтра файла:

// A filter is a sequence of independant <see cref="Regex">regular expressions</see> separated by semi-colons ';'
// Each expression can be prefixed by a plus '+' sign or a minus '-' sign to denote the expression
// is intended to include or exclude names.  If neither a plus or minus sign is found include is the default
// A given name is tested for inclusion before checking exclusions.  Only names matching an include spec
// and not matching an exclude spec are deemed to match the filter.
// An empty filter matches any name.
// </summary>
// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
// "+\.dat$;-^dummy\.dat$"

так для файла, названного myfile.dat, Вы могли использовать "+.*myfile\.dat$" в качестве своего фильтра файла.

15
ответ дан 27 November 2019 в 16:39
поделиться

Примечание - этот ответ предлагает альтернативу <часу> SharpZipLib

, DotNetZip имеет строковый индексатор на классе ZipFile для создания этого действительно легким.

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
   zip["NameOfFileToUnzip.txt"].Extract();
 }

Вы не должны играть с inputstreams и outputstreams и так далее, только для извлечения файла. С другой стороны, если Вы хотите поток, можно получить его:

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
   Stream s = zip["NameOfFileToUnzip.txt"].OpenReader();
   // fiddle with stream here
 }

можно также сделать подстановочные извлечения.

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
     // extract all XML files in the archive
     zip.ExtractSelectedEntries("*.xml");
 }

существуют перегрузки для определения overwrite/no-overwrite, различных целевых каталогов, и т.д. Можно также извлечь на основе критериев кроме имени файла. Например, извлеките все файлы, более новые, чем 15 января 2009:

     // extract all files modified after 15 Jan 2009
     zip.ExtractSelectedEntries("mtime > 2009-01-15");

И можно объединить критерии:

     // extract all files that are modified after 15 Jan 2009) AND  larger than 1mb
     zip.ExtractSelectedEntries("mtime > 2009-01-15 and size > 1mb");

     // extract all XML files that are modified after 15 Jan 2009) AND  larger than 1mb
     zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15 and size > 1mb");

Вы не должны извлекать файлы, которые Вы выбираете. Можно просто выбрать их и затем принять решения о том, извлечь ли или нет.

    using (ZipFile zip1 = ZipFile.Read(ZipFileName))
    {
        var PhotoShopFiles = zip1.SelectEntries("*.psd");
        // the selection is just an ICollection<ZipEntry>
        foreach (ZipEntry e in PhotoShopFiles)
        {
            // examine metadata here, make decision on extraction
            e.Extract();
        }
    }
7
ответ дан 27 November 2019 в 16:39
поделиться

У меня есть возможность VB.NET, для извлечения определенных файлов из архиваторов Zip. Комментарии на испанском. Возьмите путь к Zip-файлу, имя файла, которое вы хотите извлечь, пароль, если необходимо. Извлечь по исходному пути, если для OriginalPath установлено значение 1, или использовать DestPath, если OriginalPath = 0. Следите за материалом «ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream» ...

Это выглядит следующим образом:

''' <summary>
''' Extrae un archivo específico comprimido dentro de un archivo zip
''' </summary>
''' <param name="SourceZipPath"></param>
''' <param name="FileName">Nombre del archivo buscado. Debe incluir ruta, si se comprimió usando guardar con FullPath</param>
''' <param name="DestPath">Ruta de destino del archivo. Ver parámetro OriginalPath.</param>
''' <param name="password">Si el archivador no tiene contraseña, puede quedar en blanco</param>
''' <param name="OriginalPath">OriginalPath=1, extraer en la RUTA ORIGINAL. OriginalPath=0, extraer en DestPath</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExtractSpecificZipFile(ByVal SourceZipPath As String, ByVal FileName As String, _
ByVal DestPath As String, ByVal password As String, ByVal OriginalPath As Integer) As Boolean
    Try
        Dim fileStreamIn As FileStream = New FileStream(SourceZipPath, FileMode.Open, FileAccess.Read)
        Dim fileStreamOut As FileStream
        Dim zf As ZipFile = New ZipFile(fileStreamIn)

        Dim Size As Integer
        Dim buffer(4096) As Byte

        zf.Password = password

        Dim Zentry As ZipEntry = zf.GetEntry(FileName)

        If (Zentry Is Nothing) Then
            Debug.Print("not found in Zip")
            Return False
            Exit Function
        End If

        Dim fstr As ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream
        fstr = zf.GetInputStream(Zentry)

        If OriginalPath = 1 Then
            Dim strFullPath As String = Path.GetDirectoryName(Zentry.Name)
            Directory.CreateDirectory(strFullPath)
            fileStreamOut = New FileStream(strFullPath & "\" & Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)
        Else
            fileStreamOut = New FileStream(DestPath + "\" + Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)
        End If


        Do
            Size = fstr.Read(buffer, 0, buffer.Length)
            fileStreamOut.Write(buffer, 0, Size)
        Loop While (Size > 0)

        fstr.Close()
        fileStreamOut.Close()
        fileStreamIn.Close()
        Return True
    Catch ex As Exception
        Return False
    End Try

End Function
2
ответ дан 27 November 2019 в 16:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: