Search code examples
uwpwinrt-xaml

How to copy file to another folder and remove the file


I used below code and get error message:

{"Error HRESULT E_FAIL has been returned from a call to a COM component."}

If I use this, it will work provided there is no similiar file exits.

await targetFile.CopyAsync(folder, strfilenm);

public static async void CopyTheFile(StorageFolder Subfdl, string strfilenm)
        {
            string strPath = "C:\\Users\\XYZUser\\Documents\\MyStuffBU";

            StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(strPath);
            var targetFile = await Subfdl.GetFileAsync(strfilenm);

            await targetFile.CopyAndReplaceAsync(targetFile);            
            await targetFile.DeleteAsync();     

        }

How to do this:

copy the file from the current folder (in C:) and to another folder (in C:) even there could be similar filename exits later, remove the file in the current folder

Thanks.


Solution

  • You are trying to replace the file with a copy of itself with this line:

    await targetFile.CopyAndReplaceAsync(targetFile); 
    

    See the documentation of CopyAndReplaceAsync.

    You should use MoveAsync or one of it's overrides. This way you won't have to call DeleteAsync neither, since the file will be moved.