I need to copy a file to another path, leaving the original where it is.
I also want to be able to rename the file.
Will FileInfo's CopyTo method work?
I need to copy a file to another path, leaving the original where it is.
I also want to be able to rename the file.
Will FileInfo's CopyTo method work?
Have a look at File.Copy()
Using File.Copy you can specify the new file name as part of the destination string.
So something like
File.Copy(@"c:\test.txt", @"c:\test\foo.txt");
See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
You could also use File.Copy
to copy and File.Move
to rename it afterwords.
// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);
// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
// However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
// throw new IOException("Failed to rename file after copying, because destination file exists!");
EDIT
Commented out the "rename" code, because File.Copy
can already copy and rename in one step, as astander noted correctly in the comments.
However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.
File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo
, here's a sample:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten