1

I want to launch a dialog box in MFC, select multiple files and show this file to the user and later copy this file to another location.

I have written this code to try and achieve this:

CFileDialog fOpenDlg(TRUE,"", " ", OFN_ALLOWMULTISELECT|OFN_FILEMUSTEXIST, 
"Capture file (*.cap)|*.cap|", this);

fOpenDlg.m_pOFN->lpstrTitle="Import file";

fOpenDlg.m_pOFN->lpstrInitialDir="Desktop";

if(fOpenDlg.DoModal()==IDOK)
{
    POSITION pos=fOpenDlg.GetStartPosition();
    while(pos)
    {
        CString PathName=fOpenDlg.GetNextPathName(pos);
        CString strFileName=fOpenDlg.GetFilename();
        AfxMessageBox(strFileName);
    }
}

The problem with this is that when I select single file it gives file name but when I select multiple files it does not give any file name ?

I do not know the reason why?

John Sibly
  • 22,782
  • 7
  • 63
  • 80
JAI SINGH
  • 27
  • 6

2 Answers2

0

The function GetFileName does not work for multiple selected files (see this MSDN page explaining about the use of OFN_ALLOWMULTISELECT).

Use the GetStartPosition / GetNextPathName functions as you are already doing in your code snippet.

If you just want to get the filename, and not the full path to each file, consider using the splitpath function as shown in this example: splitpath quesion on stackoverflow

Edit: To wrap up getting the file name, you could add in a function similar to:

CString GetFileName(const CString& filePath)
{
    TCHAR   drive[_MAX_DRIVE];
    TCHAR   dir[_MAX_DIR];
    TCHAR   fname[_MAX_FNAME];
    TCHAR   ext[_MAX_EXT];

    _tsplitpath_s(filePath, drive, dir, fname, ext);

    CString fileName;
    fileName.Format(_T("%s%s"), fname, ext);
    return fileName;
}

Then replace the code that displays the message box with:

AfxMessageBox(GetFileName(PathName));

That worked for me when I added it to your code example.

Community
  • 1
  • 1
John Sibly
  • 22,782
  • 7
  • 63
  • 80
0

What you want is:

CFileDialog fOpenDlg(TRUE,"", " ", OFN_ALLOWMULTISELECT|OFN_FILEMUSTEXIST, 
"Capture file (*.cap)|*.cap|", this);

fOpenDlg.m_pOFN->lpstrTitle="Import file";

fOpenDlg.m_pOFN->lpstrInitialDir="Desktop";

if(fOpenDlg.DoModal()==IDOK)
{
    POSITION pos=fOpenDlg.GetStartPosition();
    while(pos)
    {
        CString PathName=fOpenDlg.GetNextPathName(pos);
        CString strFileName= ::PathFindFileName(PathName);
        AfxMessageBox(strFileName);
    }
}

Notice the CString strFileName= ::PathFindFileName(PathName); line.

sergiol
  • 4,122
  • 4
  • 47
  • 81