Generate new file name for duplicate files


/ Published in: C#
Save to your folder(s)

Modifies the file name in case an existing filename is in the specified path.
(Ex: myfile.dat
myfile(1).dat
myfile(2).dat
myfile(3).dat)


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Generates a new path for duplicate filenames.
  3. /// </summary>
  4. /// <param name="path">The path.</param>
  5. /// <returns></returns>
  6. private string GetNewPathForDupes( string path )
  7. {
  8. string directory = Path.GetDirectoryName( path );
  9. string filename = Path.GetFileNameWithoutExtension( path );
  10. string extension = Path.GetExtension( path );
  11. int counter = 1;
  12.  
  13. string newFullPath;
  14.  
  15. do
  16. {
  17. string newFilename = "{0}({1}).{2}".FormatWith( filename, counter, extension );
  18. newFullPath = Path.Combine( directory, newFilename );
  19. counter++;
  20. } while ( System.IO.File.Exists( newFullPath ) );
  21.  
  22. return newFullPath;
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.