Imports System.IO
Imports System.IO.Compression
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim lngRet As Long = DeCompressFile("C:\TEST\hogohoge.txt.gz")
If (lngRet = 0) Then
MessageBox.Show("解凍処理が失敗しました。")
Else
MessageBox.Show("解凍後は" & lngRet.ToString & "バイトになりました。")
End If
End Sub
''' <summary>
''' GZipStreamを利用してファイル(gz)を解凍して保存する
''' </summary>
''' <param name="filepathname">解凍対象ファイルパス名</param>
''' <param name="outpath">出力フォルダ</param>
''' <returns>解凍後のファイルサイズ(byte)
''' 処理が失敗した場合は0</returns>
''' <remarks></remarks>
Private Function DeCompressFile(ByVal filepathname As String, _
Optional ByVal outpath As String = "") As Long
Try
DeCompressFile = 0
''拡張子チェック(gz)
If (Path.GetExtension(filepathname).ToLower <> ".gz") Then
Return 0
End If
''入力ファイル有無チェック
If (My.Computer.FileSystem.FileExists(filepathname) = False) Then
Return 0
End If
''出力ファイルパス
If (outpath = "") Then
outpath = My.Computer.FileSystem.CombinePath( _
Path.GetDirectoryName(filepathname), _
Path.GetFileNameWithoutExtension(filepathname))
Else
outpath = My.Computer.FileSystem.CombinePath( _
outpath, _
Path.GetFileNameWithoutExtension(filepathname))
End If
''ファイル内容を取得
Using inFile As New FileStream(filepathname, FileMode.Open, _
FileAccess.Read, FileShare.Read)
Using decompStream As New GZipStream(inFile, CompressionMode.Decompress, True)
''
Const blockSize As Integer = 100000
Dim inBuffer(0) As Byte
Dim offset As Integer = 0
Dim totalCount As Integer = 0
Do
ReDim Preserve inBuffer(Cint(inBuffer.GetLongLength(0) - 1 + blockSize))
Dim bytesRead As Integer = decompStream.Read(inBuffer, offset, blockSize)
If bytesRead = 0 Then
Exit Do
End If
offset += bytesRead
totalCount += bytesRead
Loop
''バッファサイズ調整
ReDim Preserve inBuffer(totalCount - 1)
decompStream.Close()
inFile.Close()
''ファイルを出力
Using outFile As New FileStream(outpath, _
FileMode.Create, FileAccess.Write)
outFile.Write(inBuffer, 0, inBuffer.Length)
DeCompressFile = outFile.Length
outFile.Close()
End Using
End Using
End Using
Catch ex As Exception
Return 0
End Try
End Function
End Class
|