Click here to Skip to main content
15,894,460 members
Articles / Desktop Programming / MFC
Article

Copy, Move and Delete files and directories without using SHFileOperation

Rate me:
Please Sign up or sign in to vote.
4.16/5 (27 votes)
30 Mar 20042 min read 284.8K   12.7K   61   37
Class that allows file operations without using SHFileOperation

Image 1

Introduction

There are no methods in VS for copying files and directories (with subdirectories and files) based on API functions. It's necessary to use SHFileOperation function from shell to do it. Sometimes it's inconvenient and this code is designed to fill this space.

Background

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 CString and 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 FindFirstFile and FindNextFile instead of CFileFind class).

Features

  1. 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.
  2. 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.
  3. 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.
  4. AskIfReadonly is not set: If you try to delete file with readonly attribute it will delete without any question.
  5. 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 destination path.

Using the code

  1. Add files FileOperations.cpp and FileOpearations.h to your project.
  2. In the file where you want to use this class add
    #include "FileOpearations.h"
  3. Create CFileOperation object and use it.

Sample code

#include "stdafx.h"
#include "FileOperations.h"
//
// this code copy 'c:\source' directory and 
// all it's subdirectories and files
// to the 'c:\dest' directory. 
//
CFileOperation fo;      // create object
fo.SetOverwriteMode(false); // reset OverwriteMode flag (optional)
if (!fo.Copy("c:\\source", "c:\\dest")) // do Copy
{
    fo.ShowError(); // if copy fails show error message
}
//
// this code delete 'c:\source' directory and 
// all it's subdirectories and files.
//
fo.SetAskIfReadOnly();   // set AskIfReadonly flag (optional)
if (!fo.Delete("c:\\source")) // do Copy
{
    fo.ShowError(); // if copy fails show error message
}

If some operation failed you can get error code or error string or show error message (see functions, GetErrorCode(), GetErrorString() and ShowError() accordingly).

For more information you can see demo project.

Available methods

  • 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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Poor Copy() functionality ! Pin
Fess66231-Aug-04 22:51
Fess66231-Aug-04 22:51 
GeneralRe: Poor Copy() functionality ! Pin
ChristophF31-Aug-04 23:04
ChristophF31-Aug-04 23:04 
GeneralCopyFileEx error Pin
rzabek10-Jul-04 4:08
rzabek10-Jul-04 4:08 
GeneralRe: CopyFileEx error Pin
Fess66219-Jul-04 4:03
Fess66219-Jul-04 4:03 
GeneralWild Cards *.*, *.dat, MyFile.* not supported Pin
David29984-Apr-04 13:03
David29984-Apr-04 13:03 
GeneralRe: Wild Cards *.*, *.dat, MyFile.* not supported Pin
Fess66220-Jul-04 4:47
Fess66220-Jul-04 4:47 
GeneralVery dangerous code Pin
Joe Sonderegger1-Apr-04 19:38
Joe Sonderegger1-Apr-04 19:38 
GeneralRe: Very dangerous code Pin
Member 368078526-Jun-09 9:32
Member 368078526-Jun-09 9:32 
I disagree completely... I like the fact that the method used here bypasses the shell, and attendant rigamarole like the "Recycle Bin." As a result, it's probably several orders of magnitude faster (and more likely to actually complete successfully) than the method you propose.

In calling this code "dangerous," I guess you're referring to the risk that someone might not be able to recover something from the Recycle Bin. But presumably this irrecoverable "something" would have been deleted by some application other than Explorer, and I simply do not expect to see such things in the Recycle Bin. In fact, if I opened up the Recycle Bin and saw a bunch of unfamiliar files I didn't remember deleting, I would find that unexpected. Also, I would find it wasteful.

More generally, I would make the statement to you that in my opinion heroic code is bad code, even if aspects of the resultant functionality seem "cool." By "heroic," I mean code that requires the developer to be super-clever in order that the user can behave stupidly.

I think a good example of the "hero" anti-pattern is Microsoft Word... it "notices" from another thread if you are trying to type a letter, automatically places sections of your document in and out of outline mode, tries to automatically to clean up your mess if you don't save your work or shut down properly, etc. It clearly has a great deal of slow, complex code designed to allow the user to be an idiot.

I think the ultimate example of non-heroic code is UNIX. Everyone using it is on a much more equal footing. Neither the writer of, nor the users of, say, GCC or GREP is allowed to behave idiotically. Nor did the writers of these tools waste much effort planning for stupidity.

Personally, I want my software to be like UNIX, not like Word. Beyond the dividends paid in the form of speed and predictability, I just like the UNIX attitude better. It places all of us in the same metaphorical boat, and helps computer users of all sorts find more of a common ground. That is something the PC world - with its "you've got mail" emphasis on keeping Grandma as dumb as possible - has really lost sight of.

The sad thing is that the practitioners of the hero anti-pattern act like they're providing a valuable service, and for the most part the marketplace seems willing to go along with this ("oooh.. the new Windows lets you bring back deleted files! And it has a search dog!").
GeneralNice, but a few suggestions... Pin
James R. Twine31-Mar-04 4:38
James R. Twine31-Mar-04 4:38 
GeneralNice! Pin
khb30-Mar-04 20:20
khb30-Mar-04 20:20 
GeneralRe: Nice! Pin
c2j27-Apr-04 3:49
c2j27-Apr-04 3:49 
GeneralRe: Nice! Pin
khb7-Apr-04 4:06
khb7-Apr-04 4:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.