There are no methods in VS for copying files and directories (with subdirectories and files)
based on API functions. It's necessary to use
function from shell to do it. Sometimes it's inconvenient and this code is designed to fill this space.
This code is a simple wrapper over API functions that allow file and dir
operations. Recursion methods are the base of this code. MFC was used for
simplification of process (only
CFileFind classes used from).
If you don't want to use MFC in your project you can change MFC calls to API
calls (use STL
string and API functions
OverwriteMode is set: If you copy file to the existing file or to the folder where exist file
with the same name, it will overwrite it.
OverwriteMode is not set: If you copy file to the existing file or to the folder where exist file
with the same name, it will create new file with name
'Copy of ORIGINAL_FILE_NAME'. If file 'Copy of ORIGINAL_FILE_NAME' already
exists too, it will create new file with name 'Copy (2) of ORIGINAL_FILE_NAME'
and so on.
AskIfReadonly is set: If you try to delete file with readonly attribute the warning
message will be
shown. During 'replace' operation this flag is ignored.
AskIfReadonly is not set: If you try to delete file with readonly attribute it will delete without
- Path presentation: It is unimportant how you represent the path with '\' on end or without it.
For example you can set 'c:\\1' or 'c:\\1\\' it's the same. You can copy file
to file, file to folder or folder to folder. Just set the source path and
Using the code
- Add files FileOperations.cpp and FileOpearations.h to your project.
- In the file where you want to use this class add
CFileOperation object and use it.
if (!fo.Copy("c:\\source", "c:\\dest"))
If some operation failed you can get error code or error string or
show error message (see functions,
For more information you can see demo project.
bool Delete(CString sPathName); // delete file or folder
bool Copy(CString sSource, CString sDest); // copy file or folder
bool Replace(CString sSource, CString sDest); // move file or folder
bool Rename(CString sSource, CString sDest); // rename file or folder
CString GetErrorString(); // return error description
DWORD GetErrorCode(); // return error code
void ShowError(); // show error message
void SetAskIfReadOnly(bool bAsk = true); // sets behavior for readonly files(folders)
bool IsAskIfReadOnly(); // return current behavior for readonly files(folders)
void SetOverwriteMode(bool bOverwrite = false); // sets overwrite mode on/off
bool IsOverwriteMode(); // return current overwrite mode
bool IsAborted(); // return true if operation was aborted