酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Windows MobileでSharpZipLibを使ってZip形式のアーカイブを作成(圧縮)する

SharpZipLibを使用してZip形式のアーカイブを作成(圧縮)します。ここでは、SharpZipLibのバージョンは0.85.5を使用しています。

指定したフォルダ配下のファイルパスの一覧を作成して、アーカイブを作成します。

|vb| Private Function GetFilePathList(ByVal dirPath As String) As List(Of String) Dim list As New List(Of String)

' ディレクトリパスからファイルの一覧を取得する
Dim dirInfo As New System.IO.DirectoryInfo(dirPath)

' ファイル一覧のディレクトリ名だけをリストへ追加していく
Dim dirs As System.IO.DirectoryInfo() = dirInfo.GetDirectories()
For Each dir As System.IO.DirectoryInfo In dirs
    list.AddRange(GetFilePath(dir.FullName))
Next dir

' ファイル一覧のパス名だけをリストに順次追加していく
Dim files As System.IO.FileInfo() = dirInfo.GetFiles()
For Each fileInfo As System.IO.FileInfo In files
    If (System.IO.File.Exists(fileInfo.FullName)) Then
        list.Add(fileInfo.FullName)
    End If
Next fileInfo

Return list

End Function ||<

|vb| Private Sub CompactionZip(ByVal dirPath As String, _ ByVal zipPath As String, _ ByVal level As Integer, _ Optional ByVal password As String = "")

' ディレクトリ配下全てのファイルパスを取得する
Dim filePaths As List(Of String) = GetFilePathList(dirPath)

Using writer As New FileStream(zipPath, FileMode.Create, _
                               FileAccess.Write, FileShare.Write), _
      zos As New ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer)

    ' 圧縮レベルを設定する
    zos.SetLevel(level)
    ' パスワードを設定する
    zos.Password = password

    ' Zipにファイルを追加する
    For Each file As String In filePaths

        'ファイルをバッファに読み込む
        Dim buffer As Byte() = Nothing
        Using fStrm As New FileStream(file, FileMode.Open, _
                                      FileAccess.Read, FileShare.Read)
            Dim tempBuf(fStrm.Length - 1) As Byte
            fStrm.Read(tempBuf, 0, tempBuf.Length)
            buffer = tempBuf
        End Using

        ' 追加する要素のヘッダを作成する
        Dim f As String = file.Remove(0, dirPath.Length)
        f = f.Replace("\", "/")
        Dim ze As New ICSharpCode.SharpZipLib.Zip.ZipEntry(f)
        With ze
            .Size = buffer.Length
            .DateTime = DateTime.Now
        End With

        ' 要素のヘッダを追加してデータを書き込む
        zos.PutNextEntry(ze)
        zos.Write(buffer, 0, buffer.Length)
    Next file
End Using

End Sub ||<

|vb| Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click

' 作成するZIPファイルの設定
Dim zipPath As String = "C:\test.zip"
' 圧縮するファイルの設定
Dim dirPath As String = "C:\dir"

' Windows Mobileで使う場合は、ドライブの概念が無いので注意する
'' 作成するZIPファイルの設定
'Dim zipPath As String = "\test.zip"
'' 圧縮するファイルの設定
'Dim dirPath As String = "\dir"

' ディレクトリをZipアーカイブを作成する(無圧縮:0)
CompactionZip(dirPath, zipPath, 0)

End Sub ||<

ボタンを押下するとディレクトリ配下を無圧縮のアーカイブを作成します。

関連記事