Last active
October 27, 2017 19:43
-
-
Save dsappet/5f09654dc2a85d9faf01abe84f155b8e to your computer and use it in GitHub Desktop.
SafeMoveTo is a moveTo function that moves a file but if the destination file already exists it appends _i to the end of the filename until i is an int which causes the filename not to exist in directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace EdiService.Extentions | |
| { | |
| public static class FileInfoExtensions | |
| { | |
| // destination shall be a full destination file name | |
| public static void SafeMoveTo(this FileInfo source, FileInfo destination) | |
| { | |
| int i = 0; | |
| var destinationString = destination.FullName; | |
| while (File.Exists(destinationString)) | |
| { | |
| i++; | |
| destinationString = Path.Combine(destination.DirectoryName ?? "", | |
| $"{Path.GetFileNameWithoutExtension(destination.Name)}_{i}.{destination.Extension}"); | |
| } | |
| source.MoveTo(destinationString); | |
| } | |
| public static void SafeMoveTo(this FileInfo source, string destination) | |
| { | |
| var destinationFileInfo = new FileInfo(destination); | |
| source.SafeMoveTo(destinationFileInfo); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment