MFC Save file dialog
I am writing an MFC C++ application that has a Save As button for saving a .txt
file to the disc. With it I am trying to add an extra verification for file overwriting (if a file with the same filename exists, then it should query the user 开发者_开发技巧if he wants to overwrite the old file or not). I have tried this with the below code, but it doesn't really work. When I click No on the MessageBox, it should reopen the Save As file dialog, but instead it gives me two errors: the first one is Debug assertion failed
, and the second one is Encountered an improper argument
. How should I do this better? This is the code:
char strFilter[] = { "Text Files (*.txt)|*.txt|" };
CFileDialog FileDlg(FALSE, CString(".txt"), NULL, 0, CString(strFilter));
while(true)
{
if( FileDlg.DoModal() == IDOK ) // this is the line which gives the errors
{
agendaName = FileDlg.GetFileName(); //filename
agendaPath = FileDlg.GetFolderPath(); //filepath (folders)
if(model->agendaExists(CSToString(agendaPath+TEXT("\\")+agendaName))) // there is another file called the same way
{
if(MessageBox(TEXT("A file with the specified name already exists. Overwrite?"), TEXT("File exists"), MB_YESNO) != 6) // user clicked NO (do not overwrite file)
{
continue;
}
}
model->sendToFile(CSToString(agendaPath+TEXT("\\")+agendaName)); // the file is unique so the agenda named agendaName found at path agendaPath is saved
return;
}
}
It should be mentioned that the errors occur on line 7 and only on the second loop through the while
.
CFileDialog can detect itself if a file exists and prompt the user for overwriting.
explicit CFileDialog(
BOOL bOpenFileDialog,
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
LPCTSTR lpszFilter = NULL,
CWnd* pParentWnd = NULL,
DWORD dwSize = 0
);
Just pass OFN_OVERWRITEPROMPT for the flags.
As for your problem, run in Debugger and when you get that assertion press the Retry button to see where the problem comes from (you'll probably have to look through the call stack also). Maybe you should try putting this in the while loop:
CFileDialog FileDlg(FALSE, CString(".txt"), NULL, 0, CString(strFilter));
You should use the OFN_OVERWRITEPROMPT
flag in the constructor. That flag is usually one of the default flags, but you have set your flags to 0. So, if you do:
CFileDialog FileDlg(FALSE, CString(".txt"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, CString(strFilter));
if (FileDlg.DoModal() == IDOK)
{
model->sendToFile(CSToString(FileDlg.GetPathName()));
}
It should work. By the way, GetPathName()
gets the full path to the selected file, so you don't need to get the folder and the file name in 2 steps.
Try including below line inside the while loop (as first line in while loop)
CFileDialog FileDlg(FALSE, CString(".txt"), NULL, 0, CString(strFilter));
This line is outside the while loop in your code
精彩评论