Backing up a file

Posted on 2004-10-31
Last Modified: 2010-04-23
How can I change the ' Backup the Data file part of this code.  I want it to do the backup but be able to edit what name the file is saved as.  Instead of having the default word "Data" and the file extension it would prompt for what they would like the file saved as and use the matching extension.  I don't know if a SaveFileDialog would do this or not since it's making a backup copy of an existing file?  any suggestions on what would be best way to go and could you provide some example code for me to try?

Imports System.IO

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()

        'This call is required by the Windows Form Designer.

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents NumericUpDown1 As System.Windows.Forms.NumericUpDown
    Friend WithEvents NumericUpDown2 As System.Windows.Forms.NumericUpDown
    Friend WithEvents NumericUpDown3 As System.Windows.Forms.NumericUpDown
    Friend WithEvents NumericUpDown4 As System.Windows.Forms.NumericUpDown
    Friend WithEvents NumericUpDown5 As System.Windows.Forms.NumericUpDown
    Friend WithEvents NumericUpDown6 As System.Windows.Forms.NumericUpDown
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
    Friend WithEvents ListBox2 As System.Windows.Forms.ListBox
    Friend WithEvents Button3 As System.Windows.Forms.Button
    Friend WithEvents Button4 As System.Windows.Forms.Button
    Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
    Friend WithEvents MostLabel As System.Windows.Forms.Label
    Friend WithEvents LeastLabel As System.Windows.Forms.Label
    Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.NumericUpDown1 = New System.Windows.Forms.NumericUpDown()
        Me.NumericUpDown2 = New System.Windows.Forms.NumericUpDown()
        Me.NumericUpDown3 = New System.Windows.Forms.NumericUpDown()
        Me.NumericUpDown4 = New System.Windows.Forms.NumericUpDown()
        Me.NumericUpDown5 = New System.Windows.Forms.NumericUpDown()
        Me.NumericUpDown6 = New System.Windows.Forms.NumericUpDown()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.ListBox1 = New System.Windows.Forms.ListBox()
        Me.ListBox2 = New System.Windows.Forms.ListBox()
        Me.Button4 = New System.Windows.Forms.Button()
        Me.Button3 = New System.Windows.Forms.Button()
        Me.MostLabel = New System.Windows.Forms.Label()
        Me.LeastLabel = New System.Windows.Forms.Label()
        Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog()
        Me.ComboBox1 = New System.Windows.Forms.ComboBox()
        CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.NumericUpDown3, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.NumericUpDown4, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.NumericUpDown5, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.NumericUpDown6, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.NumericUpDown1.Location = New System.Drawing.Point(88, 8)
        Me.NumericUpDown1.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown1.Name = "NumericUpDown1"
        Me.NumericUpDown1.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown1.TabIndex = 0
        Me.NumericUpDown1.Visible = False
        Me.NumericUpDown2.Location = New System.Drawing.Point(136, 8)
        Me.NumericUpDown2.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown2.Name = "NumericUpDown2"
        Me.NumericUpDown2.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown2.TabIndex = 1
        Me.NumericUpDown3.Location = New System.Drawing.Point(184, 8)
        Me.NumericUpDown3.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown3.Name = "NumericUpDown3"
        Me.NumericUpDown3.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown3.TabIndex = 2
        Me.NumericUpDown4.Location = New System.Drawing.Point(232, 8)
        Me.NumericUpDown4.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown4.Name = "NumericUpDown4"
        Me.NumericUpDown4.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown4.TabIndex = 3
        Me.NumericUpDown5.Location = New System.Drawing.Point(280, 8)
        Me.NumericUpDown5.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown5.Name = "NumericUpDown5"
        Me.NumericUpDown5.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown5.TabIndex = 4
        Me.NumericUpDown6.Location = New System.Drawing.Point(328, 8)
        Me.NumericUpDown6.Maximum = New Decimal(New Integer() {99, 0, 0, 0})
        Me.NumericUpDown6.Name = "NumericUpDown6"
        Me.NumericUpDown6.Size = New System.Drawing.Size(40, 20)
        Me.NumericUpDown6.TabIndex = 5
        Me.Button1.Location = New System.Drawing.Point(288, 136)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(80, 24)
        Me.Button1.TabIndex = 7
        Me.Button1.Text = "Add Entry"
        Me.Button2.Location = New System.Drawing.Point(288, 112)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(80, 24)
        Me.Button2.TabIndex = 8
        Me.Button2.TabStop = False
        Me.Button2.Text = "Erase File"
        Me.ListBox1.BackColor = System.Drawing.SystemColors.HighlightText
        Me.ListBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.ListBox1.ItemHeight = 16
        Me.ListBox1.Items.AddRange(New Object() {"Least"})
        Me.ListBox1.Location = New System.Drawing.Point(16, 72)
        Me.ListBox1.Name = "ListBox1"
        Me.ListBox1.Size = New System.Drawing.Size(112, 84)
        Me.ListBox1.TabIndex = 9
        Me.ListBox1.TabStop = False
        Me.ListBox2.BackColor = System.Drawing.SystemColors.HighlightText
        Me.ListBox2.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.ListBox2.ItemHeight = 16
        Me.ListBox2.Items.AddRange(New Object() {"Most"})
        Me.ListBox2.Location = New System.Drawing.Point(160, 72)
        Me.ListBox2.Name = "ListBox2"
        Me.ListBox2.Size = New System.Drawing.Size(112, 84)
        Me.ListBox2.TabIndex = 10
        Me.ListBox2.TabStop = False
        Me.Button4.Location = New System.Drawing.Point(288, 88)
        Me.Button4.Name = "Button4"
        Me.Button4.Size = New System.Drawing.Size(80, 24)
        Me.Button4.TabIndex = 10
        Me.Button4.TabStop = False
        Me.Button4.Text = "Restore"
        Me.Button3.Location = New System.Drawing.Point(288, 64)
        Me.Button3.Name = "Button3"
        Me.Button3.Size = New System.Drawing.Size(80, 24)
        Me.Button3.TabIndex = 9
        Me.Button3.TabStop = False
        Me.Button3.Text = "Backup"
        Me.MostLabel.Location = New System.Drawing.Point(160, 48)
        Me.MostLabel.Name = "MostLabel"
        Me.MostLabel.Size = New System.Drawing.Size(128, 16)
        Me.MostLabel.TabIndex = 12
        Me.MostLabel.Text = "Most Frequent Numbers"
        Me.LeastLabel.Location = New System.Drawing.Point(16, 48)
        Me.LeastLabel.Name = "LeastLabel"
        Me.LeastLabel.Size = New System.Drawing.Size(136, 16)
        Me.LeastLabel.TabIndex = 11
        Me.LeastLabel.Text = "Least Frequent Numbers"
        Me.ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.ComboBox1.Location = New System.Drawing.Point(8, 8)
        Me.ComboBox1.Name = "ComboBox1"
        Me.ComboBox1.Size = New System.Drawing.Size(72, 21)
        Me.ComboBox1.TabIndex = 15
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(376, 174)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.ComboBox1, Me.NumericUpDown3, Me.Button3, Me.NumericUpDown6, Me.NumericUpDown4, Me.Button4, Me.NumericUpDown2, Me.Button2, Me.Button1, Me.NumericUpDown5, Me.NumericUpDown1, Me.ListBox1, Me.ListBox2, Me.MostLabel, Me.LeastLabel})
        Me.Name = "Form1"
        Me.Text = "Project 1"
        CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.NumericUpDown3, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.NumericUpDown4, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.NumericUpDown5, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.NumericUpDown6, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub

#End Region

    Dim frequencies As Hashtable
    Dim leastOccurring As SortedList
    Dim mostOccurring As SortedList
    Dim minOccurrence As Integer
    Dim maxOccurrence As Integer
    Dim nm(5) As NumericUpDown
    Dim extension As String = ".ns6"
    Dim supportPath As String = Application.StartupPath() & "\Support Files\"
    Dim backupPath As String = supportPath & "Backups\"
    Dim fileName As String = supportPath & "Data" & extension

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim i As Integer
        For i = 1 To 100
            ListBox1.Items.Add("Item" & i)
        nm(0) = NumericUpDown1
        nm(1) = NumericUpDown2
        nm(2) = NumericUpDown3
        nm(3) = NumericUpDown4
        nm(4) = NumericUpDown5
        nm(5) = NumericUpDown6

        ComboBox1.Items.Add("1 Number")
        ComboBox1.Items.Add("3 Numbers")
        ComboBox1.Items.Add("4 Numbers")
        ComboBox1.Items.Add("5 Numbers")
        ComboBox1.Items.Add("6 Numbers")
        ComboBox1.SelectedIndex = 4

        If Not Directory.Exists(supportPath) Then
        End If
        If Not Directory.Exists(backupPath) Then
        End If
        NumericUpDown1.Visible = True
    End Sub

    Private Sub NumericUpDown_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.GotFocus, NumericUpDown2.GotFocus, NumericUpDown3.GotFocus, NumericUpDown4.GotFocus, NumericUpDown5.GotFocus, NumericUpDown6.GotFocus
        Dim nud As NumericUpDown = CType(sender, NumericUpDown)
        nud.Select(0, nud.Text.Length)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End Sub

    ' Adds the input to the Data file
    Public Sub addData()
        Dim valTotal As Integer
        Dim i As Integer
        Dim output As String

        For i = 0 To 5
            If nm(i).Enabled Then
                valTotal = valTotal + nm(i).Value
                If i = 0 Then
                    output = nm(i).Value.ToString
                    output = output & "," & nm(i).Value.ToString
                End If
            End If
        If valTotal = 0 Then
            If MessageBox.Show("Do you want to save all zeros" & vbCrLf & "to the data file?", "Please verify for me", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) <> DialogResult.Yes Then
                Exit Sub
            End If
        End If

        Dim sw As New StreamWriter(fileName, True)
        NumericUpDown1.Value = 0
        NumericUpDown2.Value = 0
        NumericUpDown3.Value = 0
        NumericUpDown4.Value = 0
        NumericUpDown5.Value = 0
        NumericUpDown6.Value = 0
    End Sub

    ' Analyze the file
    Private Sub analyzeNumbers()
        If Not File.Exists(fileName) Then
            Exit Sub
        End If
        frequencies = New Hashtable()
        Dim sr As New StreamReader(fileName)
        Dim inputLine As String
        Dim values As String()
        Dim value As String
        Dim intValue As Integer
        Dim valueFrequency As Integer
        inputLine = sr.ReadLine
        While Not (inputLine Is Nothing)
            values = Split(inputLine, ",")
            For Each value In values
                    valueFrequency = 0
                    intValue = Integer.Parse(value)
                    If frequencies.ContainsKey(intValue) Then
                        valueFrequency = CType(frequencies.Item(intValue), Integer)
                    End If
                    valueFrequency = valueFrequency + 1
                    frequencies.Item(intValue) = valueFrequency
                Catch ex As Exception
                    MessageBox.Show(inputLine, "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            inputLine = sr.ReadLine
        End While

        ' Find min and max occurrence
        Dim de As DictionaryEntry
        minOccurrence = 0
        maxOccurrence = 0
        For Each de In frequencies
            intValue = CType(de.Key, Integer)
            valueFrequency = CType(de.Value, Integer)
            If minOccurrence = 0 Then
                minOccurrence = valueFrequency
                maxOccurrence = valueFrequency
                minOccurrence = Math.Min(minOccurrence, valueFrequency)
                maxOccurrence = Math.Max(maxOccurrence, valueFrequency)
            End If

        ' Build lists of values matching min and max occurrence
        leastOccurring = New SortedList()
        mostOccurring = New SortedList()
        For Each de In frequencies
            intValue = CType(de.Key, Integer)
            valueFrequency = CType(de.Value, Integer)
            If valueFrequency = minOccurrence Then
                leastOccurring.Add(intValue, intValue)
            End If
            If valueFrequency = maxOccurrence Then
                mostOccurring.Add(intValue, intValue)
            End If

        ' Displays the results
        For Each intValue In leastOccurring.Values
        For Each intValue In mostOccurring.Values

    End Sub

    ' Erases the Data file
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim msg As String = "All data will be permanently lost." & vbCrLf & "Are you sure you want to delete the data file?"
        If MessageBox.Show(msg, "Deleting Data File", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = DialogResult.Yes Then
            If File.Exists(fileName) Then
                MsgBox("File Deleted", MsgBoxStyle.Information, "Delete Data File")
            End If
        End If
    End Sub

    ' Backup the Data file
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If Not File.Exists(fileName) Then
            MsgBox("There is no data to copy!")
            Dim n As String = Now.ToShortDateString & "@" & Format(Now.Hour, "00") & Format(Now.Minute, "00") & "hrs"
            n = n.Replace("/", "-")
            File.Copy(fileName, backupPath & "Data " & n & extension)
            MsgBox("Backup Saved!", MsgBoxStyle.Information, "Backup Notification")
        End If
    End Sub

    ' Restore Data from the backup Data
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        OpenFileDialog1.Title = "Please select a backup data file to restore from"
        OpenFileDialog1.InitialDirectory = backupPath
        OpenFileDialog1.Filter = "Backup Data files (*" & extension & ")|*" & extension

        If OpenFileDialog1.ShowDialog = DialogResult.OK Then
            Dim sourceFile As String = OpenFileDialog1.FileName
            Dim doubleCheck As String = "Your original Data will be replaced with:" & vbCrLf & sourceFile & vbCrLf & vbCrLf & "Are you sure you want to continue?"
            If MessageBox.Show(doubleCheck, "Restore From Backup Data", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = DialogResult.Yes Then
                If System.IO.File.Exists(fileName) Then
                End If
                System.IO.File.Copy(sourceFile, fileName)
            End If
        End If
    End Sub

    Private Sub ComboBox1_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged

        Dim cb As ComboBox = CType(sender, ComboBox)
        Dim selected As Integer = Integer.Parse(cb.Text.Substring(0, 1))
        Dim i As Integer

        extension = ".ns" & selected.ToString
        fileName = supportPath & "Data" & extension
        For i = 1 To 6
            If i <= selected Then
                nm(i - 1).Enabled = True
                nm(i - 1).Visible = True
                nm(i - 1).Enabled = False
                nm(i - 1).Visible = False
            End If
    End Sub

    ' Used to shuffle / randomize the output
    ' Use this code in any event handle to activate the shuffle
    ' ShuffleListbox(ListBox1)
    ' ShuffleListbox(ListBox2)
    Private Sub ShuffleListbox(ByVal lb As ListBox)
        Dim i As Integer
        Dim temp As Object
        Dim r As New Random()
        Dim rndIndex As Integer
        Dim lbCount As Integer = lb.Items.Count

        For i = 0 To lbCount - 1
            temp = lb.Items(i)
            rndIndex = r.Next(0, lbCount)
            lb.Items(i) = lb.Items(rndIndex)
            lb.Items(rndIndex) = temp
    End Sub

End Class
Question by:teamdad
    LVL 96

    Expert Comment

    by:Bob Learned
    Too much code, and too little time:  Zero in on the specific area, and it might be easier to help :)

    LVL 19

    Accepted Solution

    Instead of

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            If Not File.Exists(fileName) Then
                MsgBox("There is no data to copy!")
                Dim n As String = Now.ToShortDateString & "@" & Format(Now.Hour, "00") & Format(Now.Minute, "00") & "hrs"
                n = n.Replace("/", "-")
                File.Copy(fileName, backupPath & "Data " & n & extension)
                MsgBox("Backup Saved!", MsgBoxStyle.Information, "Backup Notification")
            End If
        End Sub


            SaveFileDialog1.DefaultExt = extension
            If SaveFileDialog1.ShowDialog = DialogResult.OK Then
                MsgBox("Backup Saved!", MsgBoxStyle.Information, "Backup Notification")
            End If

    Now here if the SaveAs file name provided through the Dialog Box has an Extension that will be used otherwise it will use the Deafault Extension. if that is OK then good But in case you want that for every file the extension should be that in the variable Extension  add these two lines before you call File.Copy

                Me.SaveFileDialog1.FileName.Remove(Me.SaveFileDialog1.FileName.IndexOf(".") + 1, 3)
                Me.SaveFileDialog1.FileName &= extension
    LVL 19

    Expert Comment

    Put these code in place of

    Dim n As String = Now.ToShortDateString & "@" & Format(Now.Hour, "00") & Format(Now.Minute, "00") & "hrs"
                n = n.Replace("/", "-")
                File.Copy(fileName, backupPath & "Data " & n & extension)
                MsgBox("Backup Saved!", MsgBoxStyle.Information, "Backup Notification")

    i.e in the ELSE part


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Suggested Solutions

    Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
    Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
    With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    913 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now