Is there an easy way to add (#) to a file name when a duplicate file name is found?

I output files in C # and want to process files saved with the same name, adding brackets and a number:

FooBar.xml
FooBar(1).xml
FooBar(2).xml
...
FooBar(N).xml

Is there an easy way to do this in .NET? And is there a special name for the design (#)?

+3
source share
8 answers

You just need to manually count and change the file names. Below (pseudo) code is dirty, but this is the main algorithm. Refactor it according to your needs.

var filenameFormat = "FooBar{0}.xml";
var filename = string.Format(filenameFormat, "");
int i = 1;
while(File.Exists(filename))
    filename = string.Format(filenameFormat, "(" + (i++) + ")");

return filename;

If you succeed, you can always simply click on DateTime.Now in the format of your choice. In any case, this is what we do for temporary files.

+14

, :

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;
}
+5
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;
}
+3
/// <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;
}

, , : log.SaveTo( GetNextFileName( log.txt ) ); log.txt log (0).txt log (1).txt log (2).txt ..

, . .

+2

LINQ-ish, Keith Dahlby: "" LINQ "" .

+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");

EDIT. , .

( ), :

string fileName = "FooBar", directory = @"C:\Output";
int no = 0;
while ( ++no > 0 && File.Exists(Path.Combine(directory, fileName + "(" + no.ToString() + ").xml")) );
0
  • , fsio.

    public static class FileInfoExt
    {
        public static FileInfo DeDupue(this FileInfo f)
        {
            string path = f.FullName;
    
            string directory = Path.GetDirectoryName(path);
            string filename = Path.GetFileNameWithoutExtension(path);
            string extension = Path.GetExtension(path);
    
            string newFullPath = path;
            IEnumerable<string> files = new DirectoryInfo(directory)
                .EnumerateFiles().Select(r => r.FullName);
    
            for (int i = 1; files.Contains(newFullPath); i++)
            {
                string newFilename = string.Format(
                    "{0}({1}){2}",
                    filename,
                    i,
                    extension);
                newFullPath = Path.Combine(directory, newFilename);
            }
    
            return new FileInfo(newFullPath);
        }
    }
    
0

, , , ( ) , , , :

string ExisitngFile = FIlePath+ FileNameWithTheExtension;
            string[] splitTheFileName= FileNameWithTheExtension.Split('.');
            string extension = splitTheFileName[1];
            string name = splitTheFileName[0];
            int counter = 1;
            while(File.Exists(FIlePath+ Path.GetFileName(name+" ("+counter +")" +"."+extension)))
            {
                counter ++;

            }
            string newFileName = name + " (" + li + ")" + "." + extension;


            file.SaveAs(FIlePath+ Path.GetFileName(newFileName));

- .

0

Source: https://habr.com/ru/post/1713399/


All Articles