VB中利用Winrar進(jìn)行文件壓縮

字號(hào):

一些數(shù)據(jù)庫(kù)文件(如access文件)在遠(yuǎn)程傳輸過程中可能由于文件比較大而影響傳遞效果。如果進(jìn)行壓縮以后再傳遞,會(huì)減少傳遞時(shí)間,避免意外的發(fā)生,同時(shí)也保證了傳遞效果。我們?cè)趬嚎s文件時(shí),最常用的壓縮工具為winrar和winzip,筆者在vb編程過程中利用winrar工具來壓縮數(shù)據(jù)庫(kù)文件,并完成遠(yuǎn)程傳輸,十分方便,在此向大家介紹一下。用winzip的方法類似。
    一、shell函數(shù)
    shell函數(shù)是vb中的內(nèi)部函數(shù),它負(fù)責(zé)執(zhí)行一個(gè)可執(zhí)行文件,返回一個(gè)variant(double),如果成功的話,代表這個(gè)程序的進(jìn)程id,若不成功,則會(huì)返回0。
    shell的語(yǔ)法:shell(pathname[,windowstyle])。
    pathname 為必需參數(shù)。類型為string,它指出了要執(zhí)行的程序名,以及任何需要的參數(shù)或命令行變量,也可以包括路徑名。
    windowstyle為可選參數(shù)。integer類型,指定在程序運(yùn)行時(shí)窗口的樣式。windowstyle有以下這些值。
    常量 值 描述
    vbhide 0 窗口被隱藏,且焦點(diǎn)會(huì)移到隱式窗口。
    vbnormalfocus 1 窗口具有焦點(diǎn),且會(huì)還原到它原來的大小和位置。
    vbminimizedfocus 2 窗口會(huì)以一個(gè)具有焦點(diǎn)的圖標(biāo)來顯示(缺省值)。
    vbmaximizedfocus 3 窗口是一個(gè)具有焦點(diǎn)的化窗口。
    vbnormalnofocus 4 窗口會(huì)被還原到最近使用的大小和位置,而當(dāng)前活動(dòng)的窗口仍然保持活動(dòng)。
    vbminimizednofocus 6 窗口會(huì)以一個(gè)圖標(biāo)來顯示,而當(dāng)前活動(dòng)的窗口仍然保持活動(dòng)。
    二、關(guān)于winrar的用法
    主要介紹以下如何在winrar中用命令行來壓縮和解壓縮文件。
    壓縮:winrar a [-switches] [files] [@file lists]
    例如你想把try.mdb壓縮到c盤下,可以winrar a c:/try.rar c:/try.mdb
    解壓縮:如果帶目錄解壓縮
    winrar x [-switches] [files] [@file lists] [destionation folder/]
    如果在當(dāng)前目錄解壓縮,即解壓縮時(shí)不寫目錄名
    winrar e [-switches] [files] [@file lists] [destionation folder/]
    例如你想把try.rar解壓縮到c盤下,可以winrar x c:/try.rar c:/try.mdb
    三、一個(gè)例子
    在vb中新建一個(gè)工程,在form1中添加兩個(gè)按鈕command1、command2和command3,把他們的caption屬性分別設(shè)為'壓縮文件'、'解壓縮文件'和'傳遞文件'。按command1時(shí)把文件try.mdb壓縮成try.rar。
    private sub command1_click()
    dim rarexe as string winrar執(zhí)行文件的位置
    dim source as string 壓縮前的原始文件
    dim target as string 壓縮后的目標(biāo)文件
    dim filestring as string shell指令中的字符串
    dim result as long
    rarexe='c:/program files/winrar/winrar'
    source='c:/try.mdb'
    target='c:/try.rar'
    filestring = rarexe & ' a ' & target & ' ' & source
    result = shell(filestring, vbhide)
    end sub
    解壓的過程類似,按command2可以把try.rar解壓生成 try.mdb。在執(zhí)行了上面的壓縮過程后,可以刪除文件try.mdb,來解壓縮重新生成try.mdb。
    private sub command2_click()
    dim rarexe as string winrar執(zhí)行文件的位置
    dim source as string 解壓縮前的原始文件
    dim target as string 解壓縮后的目標(biāo)文件
    dim filestring as string shell指令中的字符串
    dim result as long
    rarexe='c:/program files/winrar/winrar'
    source='c:/try.rar'
    target='c:/try.mdb'
    filestring = rarexe & ' x ' & source & ' ' & target
    result = shell(filestring, vbhide)
    end sub
    文件從一臺(tái)計(jì)算機(jī)傳輸?shù)搅硪慌_(tái)計(jì)算機(jī)前,應(yīng)知道另一臺(tái)計(jì)算機(jī)的名字,然后用filecopy語(yǔ)句就可以了。假設(shè)要把壓縮后try.rar傳遞到計(jì)算機(jī)名為'other'的共享目錄'want'下。
    private sub command3_click()
    dim sourcefile, destinationfile
    sourcefile ='c:/try.rar ' 指定源文件名。
    destinationfile = '//other/want/try.rar' 指定目的文件名。
    filecopy sourcefile, destinationfile 將源文件的內(nèi)容復(fù)制到目的文件中。
    end sub