I have a VB6 project in a folder called DialogTest which has one subfolder called "Subfolder".
In this folder I have placed some random text files.
The test project simply opens a dialog so user can select a text file (the initial directory is set to Subfolder directory),
then creates and saves a txt file called Test1 in the project folder (ie the app.path folder).
If the user doesn't select any file in the dialog, file is saved correctly.
If the user selects a txt file in the Subfolder directory, the program incorrectly saves Test1.txt in the Subfolder directory, not the app.path directory.
How can I correct this?
This is my complete code for the test project:
Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
"GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
Private Sub Command1_Click()
Dim OpenFile As OPENFILENAME
Dim lReturn As Long
Dim sFilter As String
OpenFile.lStructSize = Len(OpenFile)
OpenFile.hwndOwner = Form1.hWnd
OpenFile.hInstance = App.hInstance
sFilter = "Text Files (*.txt)" & Chr(0) & "*.TXT" & Chr(0)
OpenFile.lpstrFilter = sFilter
OpenFile.nFilterIndex = 1
OpenFile.lpstrFile = String(257, 0)
OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
OpenFile.lpstrFileTitle = OpenFile.lpstrFile
OpenFile.nMaxFileTitle = OpenFile.nMaxFile
OpenFile.lpstrInitialDir = App.Path & "\Subfolder"
OpenFile.lpstrTitle = "Open"
OpenFile.flags = 0
lReturn = GetOpenFileName(OpenFile)
If lReturn = 0 Then
MsgBox "User pressed Cancel Button"
MsgBox "User opened " & Trim(OpenFile.lpstrFile)
Open "Test1.txt" For Output As #1
Print #1, "abcd"
The current directory can be changed by the dialog. You either need to cache it before the dialog and change it back after, or use an absolute path when creating the file instead of creating it in the current directory.
Something else to keep in mind is that App.Path and the initial CD can be quite different. That usually happens because the program was started from a shortcut or by a file association. So you might want to cache CD instead of App.Path.