|
|
Архиваторы - Модуль работы с архиватором WinRAR или 7-Zip (+ пример)
Ещё потребуется два дополнительных модуля:
- modExecCmd - Запуск процесса и ожидание его окончания (см. ниже)
и
- modFoldersAndFiles - Модуль для работы с папками файлами (см. ниже)
Private Sub Test_modArchiv()
Const sArhiverPath As String = "C:\Program Files\WinRAR\WinRAR.exe"
Dim sPathSRS As String
Dim sPathDST As String
Dim l As Long
On Error GoTo Test_modArchiv_Err
sPathSRS = CurrentProject.Path & "\Читать!.txt"
sPathDST = CurrentProject.Path & "\Test_01\Test_modArchiv"
l = DBToArchive(sArhiverPath, sPathSRS, sPathDST)
If l > 0 Then
End If
sPathSRS = CurrentProject.Path & "\MoneyDB.mdb"
sPathDST = CurrentProject.Path & "\Test_01\Test_modArchiv"
l = DBToArchive(sArhiverPath, sPathSRS, sPathDST, True)
If l > 0 Then
End If
sPathSRS = CurrentProject.Path & "\Test_01\Test_modArchiv.zip"
sPathDST = CurrentProject.Path & "\Test_02"
l = DBFromArchive(sArhiverPath, sPathSRS, sPathDST, "MoneyDB.mdb")
If l > 0 Then
End If
sPathSRS = CurrentProject.Path & "\Test_01\Test_modArchiv.zip"
sPathDST = CurrentProject.Path & "\Test_03"
l = DBFromArchive(sArhiverPath, sPathSRS, sPathDST)
If l > 0 Then
End If
Test_modArchiv_Bye:
Exit Sub
Test_modArchiv_Err:
MsgBox "Error " & Err.Number & vbCrLf & Err.Description & vbCrLf & _
"in procedure Test_modArchiv", vbCritical, "Error!"
Resume Test_modArchiv_Bye
End Sub
Option Compare Database
Option Explicit
Public Function DBToArchive(sArchiverPath As String, strDBPath As String, _
strArcPath As String, _
Optional blCompactBefore As Boolean = False) As Long
Dim sParam As String
Dim sArchName As String
Dim i As Long
Dim str As String
Dim strDistFolder As String
Dim strCompactedDB As String
On Error GoTo DBToArchive_Error
If Dir(sArchiverPath) = "" Then
MsgBox "Не могу найти исполняемый файл архиватора:" & vbCrLf & _
sArchiverPath, vbCritical, "Нет Архиватора"
GoTo DBToArchive_Bye
End If
If Dir(strDBPath, vbNormal) = "" Then
MsgBox "Не могу найти исходный файл для помещения в архив:" & vbCrLf & _
strDBPath, vbCritical, "Нет исходного файла!"
Exit Function
End If
str = LCase(Right(sArchiverPath, 7))
Select Case str
Case "rar.exe"
sArchName = "WinRAR"
sParam = "a -m4 -afzip -ep -t -ibck -inul"
Case "7zg.exe"
sArchName = "7-Zip"
sParam = "a -tzip"
Case Else
MsgBox "Не могу определить используемый архиватор:" & vbCrLf & sArchiverPath, vbCritical, "Нет Архиватора"
GoTo DBToArchive_Bye
End Select
If FileIsFree(strDBPath) = False Then
MsgBox "Исходный файл:" & vbCrLf & _
strDBPath & vbCrLf & _
"- занят другим процессом или пользователем, архивация невозможна!", vbCritical, "Файл занят"
GoTo DBToArchive_Bye
End If
i = PrepareFolders(strArcPath)
If i > 0 Then Err.Raise i
If blCompactBefore = False Then GoTo StartArchivator
For i = Len(strDBPath) To 1 Step -1
If Mid(strDBPath, i, 1) = "\" Then
strDistFolder = Mid(strDBPath, 1, i)
Exit For
End If
Next i
For i = 1 To 999
str = strDistFolder & "db" & Format(i, "000") & ".mdb"
If Dir(str, vbNormal) = "" Then
strCompactedDB = str
Exit For
End If
Next i
DBEngine.CompactDatabase strDBPath, strCompactedDB
DoEvents
FileCopy strCompactedDB, strDBPath
DoEvents
Kill strCompactedDB
StartArchivator:
str = """" & sArchiverPath & """ " & sParam & " """ & strArcPath & """ """ & strDBPath & """"
DBToArchive = ExecCmd(str)
If DBToArchive > 0 Then
str = ArcErrDescription(DBToArchive, sArchName)
MsgBox "При создании архива:" & vbCrLf & _
strArcPath & vbCrLf & _
"Архиватор вернул ошибку:" & vbCrLf & _
str, vbCritical, "Ошибка Архиватора"
End If
DBToArchive_Bye:
Exit Function
DBToArchive_Error:
Select Case Err.Number
Case 52
MsgBox "Ошибка доступа к Архиву:" & vbCrLf & _
strArcPath, vbCritical
Case 3356
MsgBox "Файл базы данных:" & vbCrLf & _
strDBPath & vbCrLf & _
"Занят другим пользователем!", vbCritical, "Ошибка доступа"
Case Else
MsgBox "Произошла Ошибка №" & Err.Number & vbCrLf & _
"(" & Err.Description & ")" & vbCrLf & _
"В Процедуре Архивирования"
End Select
DBToArchive = Err.Number
Resume DBToArchive_Bye
End Function
Public Function DBFromArchive(strArchPath As String, strArcPath As String, strToFolder As String, _
Optional strFileName = "*.*") As Long
Dim str As String
Dim sArchName As String
Dim sParam As String
Dim sParam2 As String
On Error GoTo DBFromArchive_Error
DBFromArchive = 70
str = LCase(Right(strArchPath, 7))
Select Case str
Case "rar.exe"
sArchName = "WinRAR"
sParam = "e -ibck -o+ -inul"
Case "7zg.exe"
sArchName = "7-Zip"
sParam = "e"
sParam2 = "-aoa"
Case Else
MsgBox "Не могу определить используемый архиватор:" & vbCrLf & strArchPath, vbCritical, "Нет Архиватора"
Exit Function
End Select
If Dir(strArcPath, vbNormal) = "" Then
MsgBox "Не могу найти исходный файл архива:" & vbCrLf & _
strArcPath, vbCritical, "Нет файла архива"
Exit Function
End If
str = Dir(Mid(strToFolder, 1, 3), vbDirectory)
If Mid(strToFolder, Len(strToFolder), 1) <> "\" Then strToFolder = strToFolder & "\"
Select Case sArchName
Case "WinRAR"
str = """" & strArchPath & """ " & sParam & _
" """ & strArcPath & """ """ & strFileName & """ """ & strToFolder & """"
Case "7-Zip"
End Select
DBFromArchive = ExecCmd(str)
If DBFromArchive > 0 Then
str = ArcErrDescription(DBFromArchive, sArchName)
MsgBox "При обработке архива:" & vbCrLf & strArcPath & vbCrLf & _
"Архиватор вернул ошибку:" & vbCrLf & str, vbCritical, "Ошибка архиватора"
End If
DBFromArchive_Bye:
On Error Resume Next
Exit Function
DBFromArchive_Error:
Select Case Err.Number
Case 52
MsgBox "Ошибка доступа к папке извлечения файлов!" & vbCrLf & _
strToFolder, vbCritical
Case Else
MsgBox "Произошла Ошибка №" & Err.Number & vbCrLf & _
"(" & Err.Description & ")" & vbCrLf & _
"В Процедуре: DBFromArchive из: Module modArchives"
End Select
DBFromArchive = Err.Number
Err.Clear
Resume DBFromArchive_Bye
End Function
Private Function ArcErrDescription(intErr As Long, AName As String) As String
On Error GoTo ArcErrDescription_Error
Select Case AName
Case "WinRAR"
Select Case intErr
Case 1: ArcErrDescription = "Предупреждение. Произошли некритические ошибки."
Case 2: ArcErrDescription = "Произошла критическая ошибка."
Case 3: ArcErrDescription = "При распаковке обнаружена ошибка CRC."
Case 4: ArcErrDescription = "Предпринята попытка изменить заблокированный архив."
Case 5: ArcErrDescription = "Произошла ошибка записи на диск."
Case 6: ArcErrDescription = "Произошла ошибка открытия файла."
Case 7: ArcErrDescription = "Ошибка при указании параметра в командной строке."
Case 8: ArcErrDescription = "Недостаточно памяти для выполнения операции."
Case 9: ArcErrDescription = "Ошибка при создании файла."
Case 255: ArcErrDescription = "Операция была прервана пользователем."
Case Else: ArcErrDescription = "Неизвестная ошибка"
End Select
Case "7-Zip"
Select Case intErr
Case 0: ArcErrDescription = "No Error"
Case 1: ArcErrDescription = "Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed."
Case 2: ArcErrDescription = "Fatal Error"
Case 7: ArcErrDescription = "Command line error"
Case 8: ArcErrDescription = "Not enough memory for operation"
Case 255: ArcErrDescription = "User stopped the process"
End Select
Case Else
ArcErrDescription = "Error !!!"
End Select
ArcErrDescription_Bye:
Exit Function
ArcErrDescription_Error:
ArcErrDescription = "Неизвестная ошибка"
Err.Clear
Resume ArcErrDescription_Bye
End Function
Option Compare Database
Option Explicit
Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessID As Long
dwThreadID As Long
End Type
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal _
hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
lpApplicationName As String, ByVal lpCommandLine As String, ByVal _
lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As String, _
lpStartupInfo As STARTUPINFO, lpProcessInformation As _
PROCESS_INFORMATION) As Long
Private Declare Function CloseHandle Lib "kernel32" _
(ByVal hObject As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Private Const STARTF_USESHOWWINDOW& = &H1
Private Const NORMAL_PRIORITY_CLASS = &H20&
Private Const INFINITE = -1&
Public Function ExecCmd(cmdline$, Optional WindowStyle& = 4) As Long
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO
Dim ret As Long
With start
.cb = Len(start)
.dwFlags = STARTF_USESHOWWINDOW
.wShowWindow = WindowStyle
End With
ret = CreateProcessA(vbNullString, cmdline$, 0&, 0&, 1&, _
NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)
ret = WaitForSingleObject(proc.hProcess, INFINITE)
Call GetExitCodeProcess(proc.hProcess, ret&)
Call CloseHandle(proc.hThread)
Call CloseHandle(proc.hProcess)
ExecCmd = ret
End Function
Public Function PrepareFolders(strFilePath As String) As Long
Dim i As Integer
Dim x As Integer
Dim strTemp As String
Dim curPath As String
On Error GoTo PrepareFoldersErr
x = Len(strFilePath)
For i = 1 To x
If Mid(strFilePath, i, 1) = "\" Then
curPath = Mid(strFilePath, 1, i - 1)
If Dir(curPath, vbDirectory) = "" Then
MkDir curPath
End If
End If
Next i
Exit Function
PrepareFoldersErr:
PrepareFolders = Err.Number
Err.Clear
End Function
Public Function FileIsFree(strPath) As Boolean
Dim varFile As Variant
On Error GoTo FileIsFree_Error
varFile = FreeFile
Open strPath For Input Access Read Lock Read Write As varFile Len = 1
FileIsFree = True
FileIsFree_Bye:
On Error Resume Next
Close varFile
Exit Function
FileIsFree_Error:
Err.Clear
FileIsFree = False
Resume FileIsFree_Bye
End Function
Файл примера для тестирования и просмотра прилагается (MSA 2003 - 46Kb)
Отработает сразу если у Вас путь "C:\Program Files\WinRAR\WinRAR.exe" - существует, иначе нужно менять код ...
01. Запустить "modArchivTestDB MSA2003 vXXX.mdb"
02. Смотреть в модуле "mod00-Test" - "Private Sub Test_modArchiv()"

MSA-2003 ( 45 kB)
|
|