File.Copy allows simple file copying. When a duplicate file name is encountered, File.Copy has a third parameter to determine if the original file is overwritten or not.
Is there a built-in .Net function that allows a third option to rename the copied file and hence keep both files?. For example, the file copy would automatically rename “readme.txt” to “readme – Copy.txt” if another readme.txt already existed in the destination folder – similar to Windows Explorer functionality?
I realize it can be written but didn’t want reinvent the wheel if it exists.
Thanks in advance.
There’s nothing you can do all-in-one go with
File.Copy, however you could test if the destination exists and thenMoveinstead.Movetakes two parameters, and you can essentially rename at the same time.See Move documentation
EDIT:
Updated code above. @xanatos makes a good point about atomic operation. I made no assumptions about whether there are other processes accessing the file(s).
Note that I haven’t added other error handling for the source file being deleted before the operation begins either.