norca
norca

Reputation: 157

CFileDialog with realtive path

I currently maintenance an old MFC application and have problems with opening file dialogs. The Program has multiple different parts were the user select files for loading, eg sound, video and other program specific formats.

Opening a dialog should always open in a "specific" folder, depending on the file ending. Giving an directory path that contains "..\" will accept and the Dialog opens with the "last selected file".

CString fileDirectory = myHelper.getPath();
// fileDirectory  is now "C:\coding\svn\source\MyProgram\..\..\bin\..\data\..\Audio\"
CFileDialog FileDialog(true, _T("MP3;WAV"), _T(fileDirectory), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, _T("All music files (*.WAV;*.MP3)));

if (FileDialog.DoModal() == IDOK)
{ ... }

I use different CDialog classes (about 15, eg for editing audiofiles, for videofiles) and they all have similar code for opening dialogs like above.

How can i support the relative paths for the CFileDialog?

Upvotes: 1

Views: 1524

Answers (1)

Andrew Komiagin
Andrew Komiagin

Reputation: 6556

The CFileDialog supports setting up initial/default folder. Here is the code snippet that demonstrates how to use it:

    const TCHAR szFilter[] = _T("Parameter Files (*.npf)|*.npf|All Files (*.*)|*.*||");
    CFileDialog dlg(TRUE, _T("npf"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this); 
    CString sParametersDir(CUtility::GetParametersDir());
    dlg.m_ofn.lpstrInitialDir = sParametersDir.GetBuffer(_MAX_PATH);    
    if(dlg.DoModal() == IDOK)
    {
        m_ParametersFileEdit.SetWindowText(dlg.GetPathName());
    }

    sParametersDir.ReleaseBuffer();

Also regarding your code. There is no need to use _T() macro for CString objects. The CString class does support UNICODE automatically. The _T() macro should only be used for string literals.

You can use CPath class to normalize file path.

CPath path(sPath);
path.AddBackslash();
path.Append(_T("Config"));
path.Canonicalize();

Upvotes: 0

Related Questions