Move a file to a different drive with Go

Issue

I’m trying to move a file from my C-drive to my H-drive using os.Replace().

The code looks as follows:

func MoveFile(source string, destination string) {
    err := os.Rename(source, destination)
    if err != nil {
        fmt.Println(err)
    }
}

However, when I run the code I get the following error:

rename C:\old\path\to\file.txt H:\new\path\to\file.txt: The system cannot move the file to a different disk drive.

I found this issue on GitHub that specifies the problem but it appears that they will not change this function to allow it to move file on different disk drives.

I already searched for other possibilities to move files, but found nothing in the standard documentation or the internet.

So, what should I do now to be able to move files on different disk drives?

Solution

As the comment said, you’ll need to create a new file on the other disk, copy the contents, and then remove the original. It’s straightforward using os.Create, io.Copy, and os.Remove:

import (
    "fmt"
    "io"
    "os"
)

func MoveFile(sourcePath, destPath string) error {
    inputFile, err := os.Open(sourcePath)
    if err != nil {
        return fmt.Errorf("Couldn't open source file: %s", err)
    }
    outputFile, err := os.Create(destPath)
    if err != nil {
        inputFile.Close()
        return fmt.Errorf("Couldn't open dest file: %s", err)
    }
    defer outputFile.Close()
    _, err = io.Copy(outputFile, inputFile)
    inputFile.Close()
    if err != nil {
        return fmt.Errorf("Writing to output file failed: %s", err)
    }
    // The copy was successful, so now delete the original file
    err = os.Remove(sourcePath)
    if err != nil {
        return fmt.Errorf("Failed removing original file: %s", err)
    }
    return nil
}

Answered By – yalue

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.