Path.copyFileTo

Copy single file to destination. If destination does not exists, then file will be copied exactly to that path. If destination already exists and it is directory, then method will try to copy file inside that directory with same name. If destination already exists and it is file, then depending on rewrite param file will be owerwritten or PathException will be thrown.

struct Path
const
void
copyFileTo
(,
in bool rewrite = false
)

Parameters

dest Path

destination path to copy file to. Could be new file path, or directory where to copy file.

rewrite bool

do we need to rewrite file if it already exists?

Throws

PathException if source file does not exists or if destination already exists and it is not a directory and rewrite is set to false.

Examples

import dshould;

// Prepare temporary path for test
auto cdir = std.file.getcwd;
Path root = createTempPath();
scope(exit) {
    std.file.chdir(cdir);
    root.remove();
}

// Create test directory structure
root.join("test-file.txt").writeFile("test");
root.join("test-file-2.txt").writeFile("test-2");
root.join("test-dst-dir").mkdir;

// Test copy file by path
root.join("test-dst-dir", "test1.txt").exists.should.be(false);
root.join("test-file.txt").copyFileTo(root.join("test-dst-dir", "test1.txt"));
root.join("test-dst-dir", "test1.txt").exists.should.be(true);

// Test copy file by path with rewrite
root.join("test-dst-dir", "test1.txt").readFile.should.equal("test");
root.join("test-file-2.txt").copyFileTo(root.join("test-dst-dir", "test1.txt")).should.throwA!PathException;
root.join("test-file-2.txt").copyFileTo(root.join("test-dst-dir", "test1.txt"), true);
root.join("test-dst-dir", "test1.txt").readFile.should.equal("test-2");

// Test copy file inside dir
root.join("test-dst-dir", "test-file.txt").exists.should.be(false);
root.join("test-file.txt").copyFileTo(root.join("test-dst-dir"));
root.join("test-dst-dir", "test-file.txt").exists.should.be(true);

// Test copy file inside dir with rewrite
root.join("test-file.txt").writeFile("test-42");
root.join("test-dst-dir", "test-file.txt").readFile.should.equal("test");
root.join("test-file.txt").copyFileTo(root.join("test-dst-dir")).should.throwA!PathException;
root.join("test-file.txt").copyFileTo(root.join("test-dst-dir"), true);
root.join("test-dst-dir", "test-file.txt").readFile.should.equal("test-42");

Meta