If file already exists - what do I do then?

Contadino

New member
Joined
Nov 19, 2007
Messages
1
Programming Experience
Beginner
I want to ask the user if he wants to overwrite the file or not. If he says "no" the program continues running. How do I make it wait until he enters the new filename and presses START again?
Thanks for any suggestions,
Contadino

Here is my If then loop:

VB.NET:
 'Check if file already exists, "Do you want to overwrite?"
        If My.Computer.FileSystem.FileExists(LSVDAQ) Then
            response2 = MsgBox("File already exists, overwrite?", MsgBoxStyle.YesNo + MsgBoxStyle.Exclamation)
            If response2 = MsgBoxResult.No Then
                MyStartButton.Enabled = True
                MyStopButton.Enabled = False
                MsgBox("Enter new filename")
            ElseIf response2 = MsgBoxResult.Yes Then
                MsgBox("File  " & LSVDAQ & "  will be created")
            End If
        Else
            response2 = MsgBox("File  " & LSVDAQ & "  will be created")
        End If
 
Last edited by a moderator:
You can use this if you want:

VB.NET:
Dim saveList As New SaveFileDialog
saveList.Filter = "Text files (*.txt)|*.txt" ' Add your filter
Dim result As DialogResult = saveList.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
   Dim fs As FileStream = Nothing
   Dim writer As StreamWriter = Nothing
   Try
        fs = New FileStream(path, FileMode.Create)
        writer = New StreamWriter(fs)
        For Each item As Object In Me.ListBox1.Items
             writer.WriteLine(item)
        Next
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
     Finally
        If writer IsNot Nothing Then
           writer.Close()
           writer.Dispose()
        End If
        If fs IsNot Nothing Then
           fs.Close()
           fs.Dispose()
        End If
     End Try
End If

The SaveFileDialog object will automatically detect if the file already exists. This is just a sample from my project and I hope this will give you an Idea.
 
Last edited:
Back
Top