Guest User

Untitled

a guest
May 23rd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. FooBar.xml
  2. FooBar(1).xml
  3. FooBar(2).xml
  4. ...
  5. FooBar(N).xml
  6.  
  7. var filenameFormat = "FooBar{0}.xml";
  8. var filename = string.Format(filenameFormat, "");
  9. int i = 1;
  10. while(File.Exists(filename))
  11. filename = string.Format(filenameFormat, "(" + (i++) + ")");
  12.  
  13. return filename;
  14.  
  15. /// <summary>
  16. /// Provides a filename given if it does not exist.
  17. /// If the filename exists, provides the lowest numeric number such that
  18. /// filename-number.ext does not exist.
  19. /// </summary>
  20. public static string GetNextFilename( string desiredFilename )
  21. {
  22. // using System.IO;
  23. int num = 0;
  24. FileInfo fi = new FileInfo( desiredFilename );
  25.  
  26. string basename = fi.FullName.Substring( 0, fi.FullName.Length - fi.Extension.Length );
  27. string extension = fi.Extension;
  28.  
  29. while( fi.Exists )
  30. {
  31. fi = new FileInfo( String.Format( "{0}({1}){2}",
  32. basename,
  33. i++,
  34. extension ) );
  35. }
  36.  
  37. return fi.FullName; // or fi.Name;
  38. }
  39.  
  40. public static string GetNextFilename(this string filename)
  41. {
  42. int i = 1;
  43. string dir = Path.GetDirectoryName(filename);
  44. string file = Path.GetFileNameWithoutExtension(filename) + "{0}";
  45. string extension = Path.GetExtension(filename);
  46.  
  47. while (File.Exists(filename))
  48. filename = Path.Combine(dir, string.Format(file, "(" + i++ + ")") + extension);
  49.  
  50. return filename;
  51. }
  52.  
  53. string fileNameFormat = "FooBar{0}.xml";
  54. string fileName = "FooBar.xml";
  55. string filePath = "C:/";
  56. string[] existingFiles = Directory.GetFiles(filePath, "FooBar*.xml");
  57. int i = 1;
  58. while (existingFiles.Contains(filePath + fileName))
  59. {
  60. fileName = string.Format(fileNameFormat, "(" + i + ")");
  61. i += 1;
  62. }
  63.  
  64. Dictionary<string, int> fileNameOccurences = new Dictionary<string, int>();
  65. // ...
  66. string fileName = "FooBar";
  67. if ( fileNameOccurences.ContainsKey(fileName) ) {
  68. fileNameOccurences[fileName]++;
  69. fileName += "(" + fileNameOccurences[fileName].ToString() + ")";
  70. }
  71. else { fileNameOccurences.Add(fileName, 1); }
  72. SaveFile(fileName + ".xml");
  73.  
  74. string fileName = "FooBar";
  75. string[] fileNames = Directory.GetFiles(theDirectory, fileName + "*.xml");
  76. fileName += "(" + (fileNames.Count + 1).ToString() + ")";
  77. SaveFile(fileName + ".xml");
  78.  
  79. string fileName = "FooBar", directory = @"C:Output";
  80. int no = 0;
  81. while ( ++no > 0 && File.Exists(Path.Combine(directory, fileName + "(" + no.ToString() + ").xml")) );
Add Comment
Please, Sign In to add comment