Search code examples
c++wxwidgets

wxCopyFile; "ERROR 5: Access is denied" even when running with administrator privilages


I'm writing a very simple program which edits an XML file and copies a user specified image to the folder in which the .exe runs.

The problem I'm having is with wxCopyFile. When I first ran the program (with debug mode in Visual Studio 2019) I got "error 5: Access denied", so I tried running the .exe from the Debug folder. Again, I got the same error. Then I ran it as administrator and again I got the same error! After that, I copied the .exe at another folder, tried it with administrator privileges and once again, it didn't work!

Here is the code where the program asks the user to select his desired image:

void GUI::OnSelectImg(wxCommandEvent& event) {
    wxFileDialog* selectImage = new wxFileDialog(NULL,
        wxString("Select the country's flag..."),
        wxEmptyString,
        wxEmptyString,
        wxT("PNG image files (*.png)|*.png") //Allow only pngs!
    );

    if (selectImage->ShowModal() == wxID_CANCEL) {
        delete selectImage;
        return;
    }

    fileMGR.SetImagePath(selectImage->GetPath());
    imagePathLabel->SetLabel(selectImage->GetPath()); //Updates the label
    delete selectImage;
}

And the part with wxCopyFile

void GUI::OnAddCountry(wxCommandEvent& event) {
    //Has he specified a flag?
    if (fileMGR.GetImagePath().IsEmpty()) {
        wxMessageBox(
            wxString("You have not specified an image for the country's flag!\nSpecify one and try again!"),
            "No image selected!",
            wxOK | wxICON_ERROR,
            this
        );
        return;
    }

    if (!wxCopyFile(fileMGR.GetImagePath(), wxStandardPaths::Get().GetDataDir())) {
        wxMessageBox(
            wxString("Failed to copy the selected image!"),
            "Failed to copy the image!",
            wxOK | wxICON_ERROR,
            this
        );
        return;
    }

    //Other not important actions...
}

And here is also the error window. What I'm I doing wrong? Thanks in advance!


Solution

  • From wxCopyFile() documentation it appears that both its arguments must be file names; however, your second argument is a directory. This results in the function trying to create a file where a directory with the same name already exists, resulting into the error.

    Therefore, you need to provide a full path including the file name instead of just the directory name for the second argument too. wxCopyFile() seems to mimic CopyFile() which it uses on MSW. It can be argued that their behaviour is not the most convenient one but that would be beyond the point of this question.