|
Навигация
Реклама
RSS / MAP / W3C
Статистика
|
Как сжать файл (zip)Пример сжатия методом GZip
System.IO.Compression даёт возможность добавить функцию сжатия в ваш исходный код используя классы GZipStream и Deflate Stream Эти классы дают возможность сжатия и распаковки файлов в GZip формате. В этом примере мы создаем класс для сжатия и распаковки одного файла. Метод CompressFile считывает указаный файл и используя GZipStream сжимает его до записи в другой файл(назначения). Распаковка происходит по томуже методу за исключением того что для начала получают размер несжатого файла из архива. Требования: Visual Studio 2005. Исходный код Form1.vb
'############################################################
'# Примеры, уроки и статьи для VB #
'# http://XOD.IN.UA
'# #
'############################################################
Imports System.IO
Public Class Form1
Public Sub New()
' Этот вызов необходим для конструктора форм Windows
InitializeComponent()
m_zipUtil = New ZipUtil()
Me.OpenFileDialog1.FileName = ""
Me.SaveFileDialog1.FileName = ""
' Добавить обработчик события
AddHandler SourceFile.Textd, AddressOf Me.Source_Text
AddHandler DestinationFile.Textd, AddressOf Me.Destination_Text
End Sub
Private Sub Compress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Compress.Click
If Me.SourceFile.Text.Length > 0 And Me.DestinationFile.Text.Length > 0 Then
Try
m_zipUtil.CompressFile(Me.SourceFile.Text, Me.DestinationFile.Text + ".zip")
MessageBox.Show("Файл " & Me.SourceFile.Text & "сжат и сохранен " & Me.DestinationFile.Text, "Пример сжатия", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.DestinationFile.Text = ""
Me.SourceFile.Text = ""
Catch ex As Exception
MessageBox.Show("Ошибка сжатия" & vbCrLf & ex.Message, "Пример сжатия", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub Decompress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Decompress.Click
If Me.SourceFile.Text.Length > 0 And Me.DestinationFile.Text.Length > 0 Then
Try
m_zipUtil.DecompressFile(Me.SourceFile.Text, Me.DestinationFile.Text)
MessageBox.Show("Удачно сжато " & Me.SourceFile.Text & " to " & Me.DestinationFile.Text, "Пример сжатия", MessageBoxButtons.OK, MessageBoxIcon.Information)
=">angs/ru.js" type="text/javascript"> Me.DestinationFile.Text = ""
Me.SourceFile.Text = ""
Catch ex As Exception
MessageBox.Show("Ошибка сжатия" & vbCrLf & ex.Message, "Пример сжатия", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub BrowseSource_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseSource.Click
If Me.OpenFileDialog1.ShowDialog = DialogResult.OK Then
Me.SourceFile.Text = Me.OpenFileDialog1.FileName
Dim newFileName As String = Path.GetFileNameWithoutExtension(Me.SourceFile.Text) + ".zip"
Me.SaveFileDialog1.FileName = newFileName
End If
End Sub
Private Sub BrowseDestination_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseDestination.Click
Me.SaveFileDialog1.FileName = ""
If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
Me.DestinationFile.Text = Me.SaveFileDialog1.FileName
End If
End Sub
'Отключить обе кнопки
Private Sub Source_Text(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SourceFile.Textd
Dim bEnabled As Boolean
bEnabled = False
If (Me.SourceFile.Text.Length > 0 And Me.DestinationFile.Text.Length > 0) Then
bEnabled = True
End If
Me.Decompress.Enabled = bEnabled
Me.Compress.Enabled = bEnabled
End Sub
Private Sub Destination_Text(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DestinationFile.Textd
Dim bEnabled As Boolean
bEnabled = False
If (Me.SourceFile.Text.Length > 0 And Me.DestinationFile.Text.Length > 0) Then
bEnabled = True
End If
Me.Decompress.Enabled = bEnabled
Me.Compress.Enabled = bEnabled
End Sub
Private m_zipUtil As ZipUtil
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.LinkLabel1.LinkVisited = True
System.Diagnostics.Process.Start("http://xod.in.ua")
End Sub
End Class
Исходный код ZipUtil.vb '############################################################
'# Примеры, уроки и статьи для VB #
'# http://XOD.IN.UA #
'# #
'############################################################
Imports System.IO
Imports System.IO.Compression
Public Class ZipUtil
Public Sub CompressFile(ByVal sourceFile As String, ByVal destinationFile As String)
' Проверяем существует ли файл
If File.Exists(sourceFile) = False Then
Throw New FileNotFoundException
End If
Dim buffer As Byte() = Nothing
Dim sourceStream As FileStream = Nothing
Dim destinationStream As FileStream = Nothing
Dim compressedStream As GZipStream = Nothing
Try
' Считываем байты с источника в массив
sourceStream = New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
' Считываем значение потока в массив
buffer = New Byte(sourceStream.Length) {}
Dim checkCounter As Integer = sourceStream.Read(buffer, 0, buffer.Length)
' Открываем файл для записи
destinationStream = New FileStream(destinationFile, FileMode.OpenOr, FileAccess.Write)
' Создаем сжатый поток файла назначения.
compressedStream = New GZipStream(destinationStream, CompressionMode.Compress, True)
'Записываем сжатый поток в файл
compressedStream.Write(buffer, 0, buffer.Length)
Catch ex As ApplicationException
MessageBox.Show(ex.Message, "Во время сжатия возникли ошибки", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
' Убеждаемся что закрыли все потоки
If Not (sourceStream Is Nothing) Then
sourceStream.Close()
End If
If Not (compressedStream Is Nothing) Then
compressedStream.Close()
End If
If Not (destinationStream Is Nothing) Then
destinationStream.Close()
End If
End Try
End Sub
Public Sub DecompressFile(ByVal sourceFile As String, ByVal destinationFile As String)
' проверяем наличие файла
If File.Exists(sourceFile) = False Then
Throw New FileNotFoundException
End If
' Создаем переменные
Dim sourceStream As FileStream = Nothing
Dim destinationStream As FileStream = Nothing
Dim decompressedStream As GZipStream = Nothing
Dim quartetBuffer As Byte() = Nothing
Try
'Считываем сжатые данные
sourceStream = New FileStream(sourceFile, FileMode.Open)
decompressedStream = New GZipStream(sourceStream, CompressionMode.Decompress, True)
' Определяем длинну файла назначения
quartetBuffer = New Byte(4) {}
Dim position As Integer = CType(sourceStream.Length, Integer) - 4
sourceStream.Position = position
sourceStream.Read(quartetBuffer, 0, 4)
sourceStream.Position = 0
Dim checkLength As Integer = BitConverter.ToInt32(quartetBuffer, 0)
Dim buffer(checkLength + 100) As Byte
Dim offset As Integer = 0
Dim total As Integer = 0
' Считываем сжатые данные
While True
Dim bytesRead As Integer = decompressedStream.Read(buffer, offset, 100)
If bytesRead = 0 Then
Exit While
End If
offset += bytesRead
total += bytesRead
End While
' Записывем всё в файл назначение
destinationStream = New FileStream(destinationFile, FileMode.)
destinationStream.Write(buffer, 0, total)
' очищаем буфер
destinationStream.Flush()
Catch ex As ApplicationException
MessageBox.Show(ex.Message, "Во время сжатия возникли ошибки", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
' Убеждаемся что закрыли все потоки
If Not (sourceStream Is Nothing) Then
sourceStream.Close()
End If
If Not (decompressedStream Is Nothing) Then
decompressedStream.Close()
End If
If Not (destinationStream Is Nothing) Then
destinationStream.Close()
End If
End Try
End Sub
End Class
Страниц: 1
|

Скачать исходный код примера
