8 Replies - 439 Views - Last Post: 09 February 2019 - 10:42 AM Rate Topic: -----

#1 Amerigo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 31-May 09

back up folder with timestamp to zip

Posted 05 February 2019 - 03:55 PM

I'm trying to create a backup zip file of a folder with date/time stamp appended to the zip file name (date&time + foldername + ".zip"

I'm getting an error that the original folder is not accessible although I can add/remove files from it in other portions of my application.
I'm betting there's a far easier solution to this mess below anyway...
    Private Sub BackupBtn_Click(sender As Object, e As EventArgs) Handles BackupBtn.Click
        If EnabledLst.SelectedItems.Count > 0 Then
            For Each itm As ListViewItem In EnabledLst.SelectedItems
                Dim UserAccount As String = User 'Specify the user here = Private User As String = Environment.UserName
                Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo(itm.Tag.ToString) ' itm.Tag.tostring = folder path
                Dim FolderAcl As New DirectorySecurity
                FolderAcl.AddAccessRule(New FileSystemAccessRule(UserAccount, FileSystemRights.Modify, InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow))
                FolderAcl.SetAccessRuleProtection(False, False)
                FolderInfo.SetAccessControl(FolderAcl)
                'Private BackupDir As String = "C:\Users\" & User & "\AppData\Roaming\.minecraft\backups"
                Dim ZipFile As String = Now.ToString("yyyy-mm-dd_hh-mm-ss_") & itm.Text & ".zip" 'item.text = folder name
                Dim D As String = Trim(BackupDir & "\" & ZipFile)
                FileCompression.CompressFile(itm.Tag.ToString, D)
                itm.Tag = D
                Dim LVI As New ListViewItem With {
                    .Text = ZipFile,
                    .Tag = D
                    }
                If Not BackupsLst.Items.Contains(itm) Then
                    BackupsLst.Items.Add(LVI)
                End If
            Next
        End If
    End Sub



Public Class FileCompression
    Public Shared Sub CompressFile(ByVal sourceFile As String, ByVal destFile As String)

        Dim destStream As New FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.Read)
        Dim srcStream As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
        Dim gz As New GZipStream(destStream, CompressionMode.Compress)

        Dim bytesRead As Integer
        Dim buffer As Byte() = New Byte(10000) {}

        bytesRead = srcStream.Read(buffer, 0, buffer.Length)

        While bytesRead <> 0
            gz.Write(buffer, 0, bytesRead)

            bytesRead = srcStream.Read(buffer, 0, buffer.Length)
        End While

        gz.Close()
        destStream.Close()
        srcStream.Close()
    End Sub

    Public Shared Sub DecompressFile(ByVal sourceFile As String, ByVal destFile As String)

        Dim destStream As New FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.Read)
        Dim srcStream As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
        Dim gz As New GZipStream(srcStream, CompressionMode.Decompress)

        Dim bytesRead As Integer
        Dim buffer As Byte() = New Byte(10000) {}

        bytesRead = gz.Read(buffer, 0, buffer.Length)

        While bytesRead <> 0
            destStream.Write(buffer, 0, bytesRead)

            bytesRead = gz.Read(buffer, 0, buffer.Length)
        End While

        gz.Close()
        destStream.Close()
        srcStream.Close()


    End Sub



Is This A Good Question/Topic? 0
  • +

Replies To: back up folder with timestamp to zip

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14854
  • View blog
  • Posts: 59,272
  • Joined: 12-June 08

Re: back up folder with timestamp to zip

Posted 05 February 2019 - 04:03 PM

Please copy/paste the full error message here, and which line it is happening on.
Was This Post Helpful? 0
  • +
  • -

#3 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 201
  • View blog
  • Posts: 1,125
  • Joined: 05-December 13

Re: back up folder with timestamp to zip

Posted 05 February 2019 - 05:10 PM

What is this Now.ToString("yyyy-mm-dd_hh-mm-ss_") & itm.Text & ".zip" 'item.text = folder name ???

You can't do that, because the format of the strings provided by DateTime() method will be in the format of 05/02/2019 - 23:45 - and therein lies the problem, you can't create file names or folders with those symbols provided by the DateTime() Method. You will need to reformat your datetime return string to use string.replace() method to replace / with _ and : with -
Was This Post Helpful? 0
  • +
  • -

#4 Amerigo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 31-May 09

Re: back up folder with timestamp to zip

Posted 06 February 2019 - 07:38 PM

Sorry, I meant to do that...
Error: System.UnauthorizedAccessException: 'Access to the path 'C:\Users\echri\AppData\Roaming\.minecraft\saves\Aacumenunan Ramparts' is denied.'

   Dim srcStream As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
+


What is this Now.ToString("yyyy-mm-dd_hh-mm-ss_") & itm.Text & ".zip" 'item.text = folder name ???
This correctly changes the format to "2019-30-06_08-30-58_Aacumenunan Ramparts.zip"
Was This Post Helpful? 0
  • +
  • -

#5 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 201
  • View blog
  • Posts: 1,125
  • Joined: 05-December 13

Re: back up folder with timestamp to zip

Posted 07 February 2019 - 07:21 AM

Sorry I know what it is, what I meant to ask is, if that meant to be the path you was creating? I assumed it is... why don't you use Path.Combine? I don't have time to run your code, maybe incorporate one of these working examples ::
Attached Image
        Dim FileName As String = "Ramparts"
        Dim Extention As String = ".zip"
        Dim ZipFileDateTime As String = DateTime.Now.ToString("dd_MM_yyyy HH-mm-tt_")
        Dim AssemblyPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
        Dim PathJoin As String = Path.Combine(AssemblyPath, ZipFileDateTime & FileName & Extention)

        Using writer As System.IO.TextWriter = System.IO.File.CreateText(PathJoin)
            writer.WriteLine("Write to this file")
        End Using
Or this folder version but you will end up with lots of folders each time one is created ::
        Dim FileName As String = "Ramparts"
        Dim Extention As String = ".zip"
        Dim ZipFileDateTime As String = DateTime.Now.ToString("dd_MM_yyyy HH-mm-tt")
        Dim AssemblyPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
        Dim DateFolder As String = AssemblyPath & "\" & ZipFileDateTime
        If Not Directory.Exists(DateFolder) Then
            Directory.CreateDirectory(DateFolder)
        End If
        Dim CompleteFilePath As String = Path.Combine(DateFolder, FileName & Extention)

        Using writer As System.IO.TextWriter = System.IO.File.CreateText(CompleteFilePath)
            writer.WriteLine("Write to this file")
        End Using
This :: Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location just gets the Directory name using reflection to get the executing path of the files assembly. (Your exe) Replace the using blocks with the code to compress or decompress your file. Once you get the path correct, you should be ok. You might also find this useful :: http://www.csharp-ex...ormat-datetime/ << It is a C# link but the formats strings are the same.

This post has been edited by Sheepings: 07 February 2019 - 09:05 AM

Was This Post Helpful? 0
  • +
  • -

#6 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 201
  • View blog
  • Posts: 1,125
  • Joined: 05-December 13

Re: back up folder with timestamp to zip

Posted 07 February 2019 - 11:11 AM

I had a little bit of time to spare to have another look...

You need to write reusable code, even what I wrote to fix your paths is pure crap, but it fixes your issue and compresses your file. But since you didn't say what file you were compressing, you need to edit PathJoin variable to reflect the file. You need to use using blocks where ever possible. Wrap your main block in using blocks like this
 Using destStream As New FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.Read)


            Dim srcStream As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
            Dim gz As New GZipStream(destStream, CompressionMode.Compress)


            Dim bytesRead As Integer
            Dim buffer As Byte() = New Byte(10000) {}

            bytesRead = srcStream.Read(buffer, 0, buffer.Length)

            While bytesRead <> 0
                gz.Write(buffer, 0, bytesRead)

                bytesRead = srcStream.Read(buffer, 0, buffer.Length)
            End While
        End Using

I changed some of your code around and it does work for compressing, but it doesn't decompress, and I don't have time to figure out why, so maybe someone else can help you with that part.

Might I point out, MS MSDN have a very simple straightforward documented way of doing this, might you head over to read it :: https://docs.microso...d-extract-files you might spot something you are doing wrong.

Here is the other part I changed, where you weren't creating the paths or checking if they existed etc
        If EnabledLst.SelectedItems.Count > 0 Then
            For Each itm As ListViewItem In EnabledLst.SelectedItems
                Dim UserAccount As String = Environment.UserName 'Outputs users username
                Dim MinCraftSpecialFolder As String = GetFolderPath(SpecialFolder.ApplicationData) 'Outputs C:\Users\user\AppData\Roaming
                Dim MCBackupDir As String = ".minecraft\backups" 'Self Explanitory
                Dim MCFolder As String = ".minecraft"
                Dim CombineMMainPath As String = Path.Combine(MinCraftSpecialFolder, MCFolder)
                Dim CombineMCBackupPath As String = Path.Combine(MinCraftSpecialFolder, MCBackupDir) 'Outputs C:\Users\user\AppData\Roaming\.minecraft\backups
                Dim ZipFileDateTime As String = DateTime.Now.ToString("dd_MM_yyyy HH-mm-tt_") 'Creates a time format string which looks like 07_02_2019 16-51-PM_

                itm.Tag = CombineMCBackupPath
                If Not Directory.Exists(itm.Tag.ToString) Then 'The backup path won't exist by default, so check for its existence and create it if needed. 
                    Directory.CreateDirectory(itm.Tag.ToString)
                End If

                Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo(itm.Tag.ToString) 'Folder info for C:\Users\user\AppData\Roaming\.minecraft\backups
                Dim FolderAcl As New DirectorySecurity
                FolderAcl.AddAccessRule(New FileSystemAccessRule(UserAccount, FileSystemRights.Modify, InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow))
                FolderAcl.SetAccessRuleProtection(False, False)
                FolderInfo.SetAccessControl(FolderAcl)

                Dim PathJoin As String = Path.Combine(CombineMMainPath, "launcher_profiles" & ".json") 'Outputs C:\Users\user\AppData\Roaming\.minecraft\backups\07_02_2019 16-51-PM_Ramparts.zip
                'You didn't say what file you were backing up so you can introduce your own logic to make PathJoin reflect the path to the file you want to actually backup. I chose the launcher_profiles file.

                Dim ZipFile As String = itm.Text & ".zip" 'item.text = folder name
                Dim D As String = Trim(CombineMCBackupPath & "\" & ZipFileDateTime & ZipFile)
                FileCompression.CompressFile(PathJoin, D)
                FileCompression.DecompressFile(CombineMCBackupPath & "\" & ZipFileDateTime & ZipFile, CombineMCBackupPath)
                'itm.Tag = D
                ' Dim LVI As New ListViewItem With {
                '    .Text = ZipFile,
                '  .Tag = D
                '     }
                '       If Not BackupsLst.Items.Contains(itm) Then
                'BackupsLst.Items.Add(LVI)
                '      End If
            Next
        End If



Was This Post Helpful? 0
  • +
  • -

#7 Amerigo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 31-May 09

Re: back up folder with timestamp to zip

Posted 08 February 2019 - 10:53 AM

Thank you so much for your detailed response. I'm not backing up a single file, but the entire folder. The Minecraft worlds in the listbox are populated from worlds in the "saves" folder within ".minecraft". The backups can be made within Minecraft, however, it doesn't provide a way of restoring them without manually opening up the folders ("backups" and "saves"), and unzipping the backups, and moving to "saves". My application is intended to do this and also enable/disable specific worlds by moving them from "saves" to "disabled" so that kids can't mess up your world(s). That part is working fine.
Was This Post Helpful? 0
  • +
  • -

#8 Amerigo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 31-May 09

Re: back up folder with timestamp to zip

Posted 09 February 2019 - 09:08 AM

Sadly, I'm still getting the same error as before.
Was This Post Helpful? 0
  • +
  • -

#9 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14854
  • View blog
  • Posts: 59,272
  • Joined: 12-June 08

Re: back up folder with timestamp to zip

Posted 09 February 2019 - 10:42 AM

Are you trying to access a file that is being used by a server or still open?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1