ExtensionMethod.NET Home of 881 C#, Visual Basic, F# and Javascript extension methods

EnsureFileNameIsUnique

Ensures given file name will return a unique file name, using the format Filename - Copy, or Filename - Copy (n) where n > 1

Source

public static string EnsureFileNameIsUnique(this string intendedName)
{
 if (!File.Exists(intendedName)) return intendedName;

 FileInfo file = new FileInfo(intendedName);
 string extension = file.Extension;
 string basePath = intendedName.Substring(0, intendedName.Length - extension.Length);

 int counter = 1;

 string newPath = "";

 do
 {
 newPath = string.Format("{0} - Copy{1}{2}", basePath, counter == 1 ? "" : string.Format(" ({0})", counter), extension);

 counter += 1;
 }
 while (File.Exists(newPath));

 return newPath;
}

Example

//Move file to new location
string fileToMove = @"C:/myfiletomove.txt";
string newLocation = Path.Combine(directoryName, fileName);

//Ensure if File Exists, then File.Move will use a unique name
//In the Windows "FileName - Copy [(#)]" format
File.Move(fileToMove, newLocation.EnsureFileNameIsUnique());

Author: John Cornell

Submitted on: 5 jun. 2014

Language: C#

Type: string

Views: 6232