0

Here is a code sample to Zip up files older than 7 days in a directory and create a compressed file with the same name, then delete the existing file. In this example we will use .txt files but you can change this to suit.

e.g.

myfile1.txt ---> myfile1.zip ---> delete myfile1.txt
myfile2.txt ---> myfile2.zip ---> delete 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

Hope it is useful!

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
James
  • 900
  • 3
  • 15
  • 28
  • What is the problem that you're having. Are you having trouble making the zip file, naming the zip file, deleting the text file, etc? – Dave H Jul 08 '13 at 16:01
  • Can you post your code that zips the files? – Dave H Jul 08 '13 at 16:07
  • What is exactly the problem ? (except the missing delete part). I tested it and it works fine. It creates separate files. – David - Jul 08 '13 at 16:28
  • 1
    @David- So it does!! I have been messing around with it all day so my brain is fried! I will convert it into a HOW TO for others! – James Jul 08 '13 at 16:45

1 Answers1

0

Already had the correct code so question did not need answering - converted into a HOWTO

James
  • 900
  • 3
  • 15
  • 28