Question OpenFileDialog Question

gvaisey52

New member
Joined
Nov 7, 2011
Messages
1
Programming Experience
Beginner
Good afternoon everyone -

I am fairly new to programming (under a year) and doing it just to learn the language. I am using VB.NET via VS2010 Express and have a question about the OpenDialog call. I'm using the dialog to prompt the user to specify a folder and filename with a .zip extension. If the .zip isn't present I am populating that easily enough and returning the fully qualified path/filename to my variable.

The question I'm having is the loop I'm trying to get working so that when the file entered doesn't end with .zip have it loop until the user cancels or enters a valid filename. The problem is that I can't get the loop to end or the cancel button to actually cancel and close the dialog. My code is below and any advice is greatly appreciated.

{ STARTCODE}
Private Sub btnSelectArchive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectArchive.Click
With OpenArchive
.FileName = ""
.Title = "Enter .ZIP for Backup"
.ValidateNames = True
.InitialDirectory = tbMMDir.Text
.CheckFileExists = False
.Filter = "ZIP Files (*.zip)|"""
.DefaultExt = ".zip"
.AddExtension = True
.CheckFileExists = False
.ShowHelp = False
.ShowDialog()
End With
tbArchiveName.Text = OpenArchive.FileName.ToString
If tbArchiveName.Text.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) Then
tbArchiveName.Text = OpenArchive.FileName.ToString
Else
MessageBox.Show("Please Enter A .ZIP Extension or Nothing At All", AppName)
If OpenArchive.ShowDialog = Windows.Forms.DialogResult.OK Then
Do Until tbArchiveName.Text.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)
OpenArchive.ShowDialog()
tbArchiveName.Text = OpenArchive.FileName.ToString
Loop

Else
tbArchiveName.Text = ""
End If

End If

End Sub

{ENDCODE}
 
It is impossible for that code (when ShowDialog=OK) to return a filename without a .zip extension, if you want to know why look up in documentation the properties of OpenFileDialog class that you have used.
In the case of Filter property your pattern is not correct, you have set a description, but not an actual file filter. Check documentation.

edit: My mistake, user could add a non-default extension and AddExtension would not apply.
If you set CheckFileExists to True and a proper filter user would have to choose an existing zip.
If CheckFileExists should not apply you should instead use a SaveFileDialog, then you can use FileOK event where you validate and cancel if not right extension. User would either have to submit a 'filename.zip' or just a 'filename' or click cancel button to exit the dialog.
 
Back
Top