Welcome Guest.   Make a donation to an author on the site July 29, 2014, 01:40:07 AM  *

Please login or register.
Or did you miss your validation email?

Login with username and password (forgot your password?)
Why not become a lifetime supporting member of the site with a one-time donation of any amount? Your donation entitles you to a ton of additional benefits, including access to exclusive discounts and downloads, the ability to enter monthly free software drawings, and a single non-expiring license key for all of our programs.

You must sign up here before you can post and access some areas of the site. Registration is totally free and confidential.
The N.A.N.Y. Challenge 2014! Download dozens of custom programs!
   Forum Home   Thread Marks Chat! Downloads Search Login Register  
Pages: [1]   Go Down
  Reply  |  New Topic  |  Print  
Author Topic: C# Rename file with incrementing number - file (1).ext  (Read 152 times)
Charter Member
Posts: 10,889

Tell me something you don't know...

see users location on a map View Profile WWW Give some DonationCredits to this forum member
« on: July 25, 2014, 09:51:55 PM »

I've seen people posting code snippets, so here's one...

I was looking around for a way to increment a file name, and didn't come across anything that really worked all that well except for 1 that kind of worked. I've bolstered it up a bit & made it more robust.


You want to quickly save file.ext, but not overwrite an existing file with that name. Obviously you want to add an increment for the file name: 1, 2, 3, etc. So you end up with something like this in a folder:

file (1).ext
file (2).ext


This is a bit sloppy in a few places, but it's good enough.

NOTE: This comes out of writing some transcoding software, so the signature there is to allow passing in a file name along with a new file name extension, which is a bit sloppy for general purposes. Basically, you can change the file extension by passing in a different "ext" parameter.

If you don't want a new file extension, simply pass in an empty string for "ext".

Formatted for C# with the GeSHI Syntax Highlighter [copy or print]
  1. /// <summary>
  2. /// A function to add an incremented number at the end of a file name if a file already exists.
  3. /// </summary>
  4. /// <param name="file">The file. This should be the complete path.</param>
  5. /// <param name="ext">This can be empty.</param>
  6. /// <returns>An incremented file name. </returns>
  7. private string AppendFileNumberIfExists(string file, string ext)
  8. {
  9. // This had a VB tidbit that helped to get this started.
  10. // http://www.codeproject.com/Questions/212217/increment-filename-if-file-exists-using-csharp
  12. // If the file exists, then do stuff. Otherwise, we just return the original file name.
  13. if (File.Exists(file)) {
  14. string folderPath = Path.GetDirectoryName(file); // The path to the file. No sense in dealing with this unecessarily.
  15. string fileName = Path.GetFileNameWithoutExtension(file); // The file name with no extension.
  16. string extension = string.Empty; // The file extension.
  17. // This lets us pass in an empty string for the file extension if required. i.e. It just makes this function a bit more versatile.
  18. if (ext == string.Empty) {
  19. extension = Path.GetExtension(file);
  20. }
  21. else {
  22. extension = ext;
  23. }
  25. // at this point, find out if the fileName ends in a number, then get that number.
  26. int fileNumber = 0; // This stores the number as a number for us.
  27. // need a regex here - \(([0-9]+)\)$
  28. Regex r = new Regex(@"\(([0-9]+)\)$"); // This matches the pattern we are using, i.e. ~(#).ext
  29. Match m = r.Match(fileName); // We pass in the file name with no extension.
  30. string addSpace = " "; // We'll add a space when we don't have our pattern in order to pad the pattern.
  31. if (m.Success) {
  32. addSpace = string.Empty; // We have the pattern, so we don't add a space - it has already been added.
  33. string s = m.Groups[1].Captures[0].Value; // This is the single capture that we are looking for. Stored as a string.
  34. // set fileNumber to the new number.
  35. fileNumber = int.Parse(s); // Convert the number to an int.
  36. // remove the numbering from the string as we're constructing it again below.
  37. fileName = fileName.Replace("(" + s + ")", "");
  38. }                
  40. // Start looping.
  41. do
  42. {
  43. fileNumber += 1; // Increment the file number that we have above.
  44. file = Path.Combine(folderPath, // Combine it all.
  45. String.Format("{0}{3}({1}){2}", // The pattern to combine.
  46.  fileName,         // The file name with no extension.
  47.  fileNumber,       // The file number.
  48.  extension,        // The file extension.
  49.  addSpace));       // A space if needed to pad the initial ~(#).ext pattern.
  50. }
  51. while (File.Exists(file)); // As long as the file name exists, keep looping.
  52. }
  53. return file;
  54. }

Just one of those typical jobs that nobody should have to bother doing again.

Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker
Pages: [1]   Go Up
  Reply  |  New Topic  |  Print  
Jump to:  
   Forum Home   Thread Marks Chat! Downloads Search Login Register  

DonationCoder.com | About Us
DonationCoder.com Forum | Powered by SMF
[ Page time: 0.055s | Server load: 0.16 ]