这是一个代码示例,用于压缩目录中超过 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
希望有用!