vendredi 25 août 2017

MSDN MoveFile the Ultimate Code to Help User to know what happen

This king of function "MoveFile" is well rotten, it's made several times I have to deal with this function I remenber each time it was hell. I don't remenber the solution, so this time I will take a note for all of us.

Why this this function is so rotten, because of error message: "access denied" or "could'nt find file" wich means nothing for the user but the function failed to Move Your Files! And it is hard to find why.

Why in english? Because I did not find any solution really good in all over the documentation around the world.

If you look at his page:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365239(v=vs.85).aspx

you can see there is a probleme ; there is not enough explainations.

Embarcadero is needed in C++.

There is my code:

#define PATH_BACKUP "C:\\Temp\\"
#define PATH_BACKUP_DIR "C:\\Temp\\Save\\"
#define PATH_DIR_TO_BACKUP "C:\\MyDirectory\\Data\\Save\\"


UnicodeString backupADirectory()
{
    UnicodeString message;
    PrintLog( "backupADirectory(" );

    // If it exist, delete and recreate destination directory
    if ( TDirectory::Exists( PATH_BACKUP_DIR ) )
    {
        TDirectory::Delete( PATH_BACKUP_DIR, true ); // Recursive = true
    }

    // Directory should exist for MoveFile
    if ( TDirectory::Exists( PATH_BACKUP ) == false )
    {
        TDirectory::CreateDirectory( PATH_BACKUP );
    }

    //
    // Moves an existing file or a directory, including its children.
    // From an Existing File to a New File.
    // The New Name must not already exist.
    //
    if ( MoveFile( PATH_DIR_TO_BACKUP, PATH_BACKUP_DIR ) == 0 )
    {
        //
        // If a FileBrowser is open on a directory to backup
        // the message is: Accès refusé
        //

        LPVOID lpMsgBuf;
        FormatMessage
        (
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0,
            NULL
        );

        string smsg = ( const char* )lpMsgBuf;
        String sMsg = smsg.c_str();
        sMsg = sMsg.SubString( 0, sMsg.Length() - 2 );
        message = UnicodeStringFormat( L"Error Moving files: %s", sMsg ) ;

    }
    else
    {
        message = L"Files Moved";
    }
    return message;
}

Have Fun! And don't forget it's only software.

Aucun commentaire:

Enregistrer un commentaire