Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- FooBar.xml
- FooBar(1).xml
- FooBar(2).xml
- ...
- FooBar(N).xml
- var filenameFormat = "FooBar{0}.xml";
- var filename = string.Format(filenameFormat, "");
- int i = 1;
- while(File.Exists(filename))
- filename = string.Format(filenameFormat, "(" + (i++) + ")");
- return filename;
- /// <summary>
- /// Provides a filename given if it does not exist.
- /// If the filename exists, provides the lowest numeric number such that
- /// filename-number.ext does not exist.
- /// </summary>
- public static string GetNextFilename( string desiredFilename )
- {
- // using System.IO;
- int num = 0;
- FileInfo fi = new FileInfo( desiredFilename );
- string basename = fi.FullName.Substring( 0, fi.FullName.Length - fi.Extension.Length );
- string extension = fi.Extension;
- while( fi.Exists )
- {
- fi = new FileInfo( String.Format( "{0}({1}){2}",
- basename,
- i++,
- extension ) );
- }
- return fi.FullName; // or fi.Name;
- }
- public static string GetNextFilename(this string filename)
- {
- int i = 1;
- string dir = Path.GetDirectoryName(filename);
- string file = Path.GetFileNameWithoutExtension(filename) + "{0}";
- string extension = Path.GetExtension(filename);
- while (File.Exists(filename))
- filename = Path.Combine(dir, string.Format(file, "(" + i++ + ")") + extension);
- return filename;
- }
- string fileNameFormat = "FooBar{0}.xml";
- string fileName = "FooBar.xml";
- string filePath = "C:/";
- string[] existingFiles = Directory.GetFiles(filePath, "FooBar*.xml");
- int i = 1;
- while (existingFiles.Contains(filePath + fileName))
- {
- fileName = string.Format(fileNameFormat, "(" + i + ")");
- i += 1;
- }
- Dictionary<string, int> fileNameOccurences = new Dictionary<string, int>();
- // ...
- string fileName = "FooBar";
- if ( fileNameOccurences.ContainsKey(fileName) ) {
- fileNameOccurences[fileName]++;
- fileName += "(" + fileNameOccurences[fileName].ToString() + ")";
- }
- else { fileNameOccurences.Add(fileName, 1); }
- SaveFile(fileName + ".xml");
- string fileName = "FooBar";
- string[] fileNames = Directory.GetFiles(theDirectory, fileName + "*.xml");
- fileName += "(" + (fileNames.Count + 1).ToString() + ")";
- SaveFile(fileName + ".xml");
- string fileName = "FooBar", directory = @"C:Output";
- int no = 0;
- while ( ++no > 0 && File.Exists(Path.Combine(directory, fileName + "(" + no.ToString() + ").xml")) );
Add Comment
Please, Sign In to add comment