CFileDialog MFC class can be used to invoke the Windows Open
File and File Save As dialogs. This CFileDialog class
encapsulates the functionalities required for retrieving file names, setting
up filters, flagging over write prompts etc.,
This CFileDialog can be used in interactive MFC GUI
applications wherever we need to browse the Windows File System (and use the
file selected). The applications need not worry about the gory background
details of enumerating the folders, listing them in a GUI etc., All these
functionalities are encapsulated within CFileDialog object.
Once CFileDialog is instantiated and called, the user can be
allowed to select the file and the programmer can use the selected file. The
CFile Example explains how to
manipulate files using MFC CFile class.
CFileDialog - for File Open:
The following piece of code snippet shows how to use
CFileDialog to open text files (*.txt) and comma separated value
files(*.csv).
CFileDialog
l_SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text Files
(*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||");
int iRet = l_SampleDlg.DoModal();
CString l_strFileName;
l_strFileName = l_SampleDlg.GetPathName();
if(iRet == IDOK)
MessageBox(l_strFileName);
else
MessageBox("No File
Selected!");
The above piece of code should be used in an MFC application.
This will invoke the File Open dialog (constructed by using
CFileDialog), with filters set for listing the *.txt and *.csv files. As
seen, DoModal returns IDOK if a file is selected and Open
button is clicked. Otherwise, if cancel button is clicked, it returns
IDCANCEL.
After this DoModal, calling CFileDialog ::GetPathName returns
the file path. If only the file name is needed, a call to the function
GetFileName will be enough.
Note: Changing the First Parameter of CFileDialog to FALSE,
this dialog will become a Save As dialog.