Copy Folder on Mac and Windows

Developers can often encounter next problem: there is required files and folders manipulations which needed to be implemented in application. For one side there is enough API to do it Qt, but maybe it is too much code to handle all reads/writes, then you need to worry about some progress message, then it could be that additional thread is required because of blocking operations. So the simple operation can make “just copying” code complicated enough.

Why not use Explorer on Windows or Fnder on Mac?

Well Mac it is very simple:

void copyFolder(QString sourcePath, QString destPath)
#ifdef Q_WS_MAC
    QStringList args;
    args << "-e";
    args << "set ss to \""+sourcePath+"\"";
    args << "-e";
    args << "set ps to POSIX file ss";
    args << "-e";
    args << "set sc to \""+destPath+"\"";
    args << "-e";
    args << "set pc to POSIX file sc";
    args << "-e";
    args << "tell application \"Finder\" to duplicate items "\
            "of folder ps to folder pc with replacing";
    QProcess::startDetached("osascript", args);
#ifdef Q_WS_WIN
    QString path = QCoreApplication::applicationDirPath();
    path += "/CopyFolder.vbs";
    QStringList args;
    args << QDir::toNativeSeparators(path);
    args << QDir::toNativeSeparators(sourcePath);
    args << QDir::toNativeSeparators(destPath);
    QProcess::startDetached("wscript", args);

You can see that on Windows it requires additional step and we have to run simple vbs script which does all job: (we assume that such vbs placed near our exe)

Set args = WScript.Arguments
Source = args.Item(0)+"*.*"
Target = args.Item(1)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(Target)
objFolder.CopyHere Source, FOF_CREATEPROGRESSDLG

As result you can see Finder or Explorer progress bars and the OS will do all tasks, including producing warnings, exceptions etc...

Finder Copying Screen Shot

Explorer Copying Screen Shot

This entry was posted in Blog, Qt. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Clef two-factor authentication