Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#3.0
Hi all
Im want to save file and append the number at the end of the file name.Example if a file named test is alread saved in a folder then the next time a user tries to save another file named test then it should be saved as test(1).n the 3rd time as test(2) n so on.Currently im using the function below but i want a more better one:
 
private string GetUniqueName(string name, string folderPath)
   {
       string validatedName = name;
       int tries = 1;
       while (File.Exists(folderPath + validatedName))
       {
           validatedName = string.Format("{0} [{1}]", name, tries++);
       }
       return validatedName;
   }
This function stops at filename(2)and if a 3rd file with the same name needs to be save it can not do so.We cant we sure of the number of files with the same name a user may want to save over a period of time that is why im looking for a better approach
Thanks
Posted 14-Nov-12 15:20pm
Comments
Sergey Alexandrovich Kryukov at 14-Nov-12 22:35pm
   
Why doing so? It does not look like a reasonable idea.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi, I have coded a simple solution for you.. every time you check the file name you need to check for the latest number that's why your code is not checking beyond 1.
 
private string GetUniqueName(string name, string folderPath, string extension)
       {
           string validatedName = name;
 
           //first get all the files with the name and the number
           string [] dirs = Directory.GetFiles(folderPath, name + "*" + extension);
 
           if (dirs.Count() > 0)
           {
               Array.Sort(dirs);
               //get the lastfilename from the array
               string CurrentLastFile = dirs[dirs.Length -1];
 
               //use a regex to get the number from the lastfilename
               Match m = Regex.Match(CurrentLastFile, "\\d+");
               int number = m.Value == "" ? 0 : Convert.ToInt32(m.Value);
 
               //assign the next number in the sequence
               validatedName = string.Format("{0} [{1}]", name, number + 1);
           }
           return validatedName;
       }
 

First I am getting all the available files in the same name format from the directory then I am getting the last file name from the list and get the number associated with it. The new file name will be formed based on the last file name.. Hope you get the idea..
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Thanks everyone for your effort.The code below work well for me.Hope this can help someone else.
 
private static string numberPattern = " ({0})";
 
   public static string NextAvailableFilename(string path)
   {
       // Short-cut if already available
       if (!File.Exists(path))
           return path;
 
       // If path has extension then insert the number pattern just before the extension and return next filename
       if (Path.HasExtension(path))
           return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));
 
       // Otherwise just append the pattern to the path and return next filename
       return GetNextFilename(path + numberPattern);
   }
 
   private static string GetNextFilename(string pattern)
   {
       string tmp = string.Format(pattern, 1);
       if (tmp == pattern)
           throw new ArgumentException("The pattern must include an index place-holder", "pattern");
 
       if (!File.Exists(tmp))
           return tmp; // short-circuit if no matches

       int min = 1, max = 2; // min is inclusive, max is exclusive/untested

       while (File.Exists(string.Format(pattern, max)))
       {
           min = max;
           max *= 2;
       }
 
       while (max != min + 1)
       {
           int pivot = (max + min) / 2;
           if (File.Exists(string.Format(pattern, pivot)))
               min = pivot;
           else
               max = pivot;
       }
 
       return string.Format(pattern, max);
   }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 235
1 Sergey Alexandrovich Kryukov 120
2 Richard MacCutchan 100
3 ChauhanAjay 95
4 BotCar 95
0 Sergey Alexandrovich Kryukov 9,056
1 OriginalGriff 8,041
2 CPallini 2,613
3 Richard MacCutchan 2,221
4 Abhinav S 1,928


Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 14 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100