Trying to delete a file if exists

bfsog

Well-known member
Joined
Apr 21, 2005
Messages
50
Location
UK
Programming Experience
5-10
I am creating a backup of a access database.
The user selects the file to copy, and that file is saved in c:\autotime\backups\

If the user selects a file called test.mdb and in c:\autotime\backups\ theres a test.mdb a messagebox is displayed with yes no buttons.

if yes is pressed, delete that file and copy the one the user selected.

However, it will not delete.


VB.NET:
	Private Sub mnuFileBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileBackup.Click

		Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb"
		Me.OpenFileDialog1.InitialDirectory = "C:\"
		Try

			If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then
			 MessageBox.Show(OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\")))
			 If System.IO.File.Exists("c:\AutoTime\backups" & OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\"))) = True Then
				 MessageBox.Show("File exists. Delete?", "AutoTime: error", MessageBoxButtons.YesNo)
				 If DialogResult = DialogResult.Yes Then
					 Dim fi As New FileInfo("c:\AutoTime\backups\mydb.mdb")
					 fi.Delete()
					End If
				Else

				  File.Copy(OpenFileDialog1.FileName, "c:\AutoTime\backups" & "\" & OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\")))

				End If
			End If
		Catch

		End Try

	End Sub

Thanks in advance
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,335
Location
Sydney, Australia
Programming Experience
10+
In your code, the DialogResult you refer to in line 9 is that of the current Form, i.e. Me.DialogResult, which is DialogResult.None, not that of the MessageBox. You need to use this code:
VB.NET:
[color=Blue]If[/color] MessageBox.Show("File exists. Delete?", "AutoTime: error", MessageBoxButtons.YesNo) = DialogResult.Yes [color=Blue]Then[/color]
	[color=Green]'Delete file.[/color]
[color=Blue] End If[/color]
One more small, unrelated point. You should more correctly use MessageBoxButtons.OKCancel in this case. "Yes" means proceed with the requested action and also do something extra. "No" means proceed with the requested action but do not do something extra. "OK" means proceed with the requested action. "Cancel" means do not proceed with the requested action. In your case you are either creating the backup or not. There is no optional extra to include or not, so OKCancel is the correct button combination to use rather than YesNo.
 
Top Bottom