0

这是一个代码示例,用于压缩目录中超过 7 天的文件并创建一个具有相同名称的压缩文件,然后删除现有文件。在本例中,我们将使用 .txt 文件,但您可以根据需要进行更改。

例如

myfile1.txt ---> myfile1.zip ---> 删除 myfile1.txt
myfile2.txt ---> myfile2.zip ---> 删除 myfile2.txt

Dim NumDays As Integer = 7
Dim reportDbPath As String = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName() & "\report"
Dim fileEntries As String() = Directory.GetFiles(reportDbPath)
For Each fileName In fileEntries
    If Path.GetExtension(fileName) = ".txt" AndAlso Directory.GetCreationTime(fileName) < DateAdd(DateInterval.Day, -NumDays, Now()) Then
        Dim fi As New FileInfo(fileName)
        Dim archiveFileName As String = Path.GetFileNameWithoutExtension(fileName) & ".zip"
        Dim fsOut As FileStream = File.Create(Path.Combine(reportDbPath, archiveFileName))
        Dim zipStream As New ZipOutputStream(fsOut)
        zipStream.SetLevel(9)
        Dim newEntry As New ZipEntry(ZipEntry.CleanName(Path.GetFileName(fileName)))
        newEntry.DateTime = fi.LastWriteTime
        newEntry.Size = fi.Length
        zipStream.PutNextEntry(newEntry)
        Dim buffer As Byte() = New Byte(4095) {}
        Using streamReader As FileStream = File.OpenRead(fileName)
            StreamUtils.Copy(streamReader, zipStream, buffer)
        End Using
        zipStream.CloseEntry()
        zipStream.IsStreamOwner = True
        zipStream.Close()
        File.Delete(fileName)
    End If
Next fileName

希望有用!

4

1 回答 1

0

已经有了正确的代码,所以问题不需要回答 - 转换成 HOWTO

于 2013-07-08T16:50:28.803 回答