Mon code C # génère plusieurs fichiers texte basés sur les entrées et les enregistre dans un dossier. En outre, je suppose que le nom du fichier texte sera identique à celui de l’entrée (l’entrée ne contient que des lettres). Si deux fichiers ont le même nom, il remplace simplement le fichier précédent. Mais je veux garder les deux fichiers.
Je ne veux pas append l’heure de la date actuelle ou un nombre aléatoire au deuxième nom de fichier. Au lieu de cela, je veux le faire de la même manière que Windows. Si le nom du premier fichier est AAA.txt, le nom du deuxième fichier est AAA (2) .txt, le troisième nom du fichier sera AAA (3) .txt ….. Le nom du fichier sera AAA (N) .txt .
ssortingng[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); foreach (var item in allFiles) { //newFileName is the txt file which is going to be saved in the provided folder if (newFileName.Equals(item, SsortingngComparison.InvariantCultureIgnoreCase)) { // What to do here ? } }
Cela permettra de vérifier l’existence de fichiers avec tempFileName et d’incrémenter le nombre par un jusqu’à ce qu’il trouve un nom qui n’existe pas dans le répertoire.
int count = 1; ssortingng fileNameOnly = Path.GetFileNameWithoutExtension(fullPath); ssortingng extension = Path.GetExtension(fullPath); ssortingng path = Path.GetDirectoryName(fullPath); ssortingng newFullPath = fullPath; while(File.Exists(newFullPath)) { ssortingng tempFileName = ssortingng.Format("{0}({1})", fileNameOnly, count++); newFullPath = Path.Combine(path, tempFileName + extension); }
Avec ce code si nomfichier est “Test (3) .txt” alors il deviendra “Test (4) .txt”.
public static ssortingng GetUniqueFilePath(ssortingng filepath) { if (File.Exists(filepath)) { ssortingng folder = Path.GetDirectoryName(filepath); ssortingng filename = Path.GetFileNameWithoutExtension(filepath); ssortingng extension = Path.GetExtension(filepath); int number = 1; Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+"); if (regex.Success) { filename = regex.Groups[1].Value; number = int.Parse(regex.Groups[2].Value); } do { number++; filepath = Path.Combine(folder, ssortingng.Format("{0} ({1}){2}", filename, number, extension)); } while (File.Exists(filepath)); } return filepath; }
Les autres exemples ne prennent pas en compte le nom de fichier / extension.
Voici:
public static ssortingng GetUniqueFilename(ssortingng fullPath) { if (!Path.IsPathRooted(fullPath)) fullPath = Path.GetFullPath(fullPath); if (File.Exists(fullPath)) { Ssortingng filename = Path.GetFileName(fullPath); Ssortingng path = fullPath.Subssortingng(0, fullPath.Length - filename.Length); Ssortingng filenameWOExt = Path.GetFileNameWithoutExtension(fullPath); Ssortingng ext = Path.GetExtension(fullPath); int n = 1; do { fullPath = Path.Combine(path, Ssortingng.Format("{0} ({1}){2}", filenameWOExt, (n++), ext)); } while (File.Exists(fullPath)); } return fullPath; }
Que diriez-vous de:
int count = 1; Ssortingng tempFileName = newFileName; foreach (var item in allFiles) { if (tempFileName.Equals(item, SsortingngComparison.InvariantCultureIgnoreCase)) { tempFileName = Ssortingng.Format("{0}({1})", newFileName, count++); } }
Cela utilisera le nom de fichier d’origine s’il n’y est pas, sinon il prendra un nouveau nom de fichier avec l’index entre parenthèses (bien que ce code ne prenne pas en compte l’extension). Si le nom nouvellement généré “text (001)” est utilisé, il sera incrémenté jusqu’à ce qu’il trouve un nom de fichier non utilisé valide.
public static ssortingng AutoRenameFilename(FileInfo file) { var filename = file.Name.Replace(file.Extension, ssortingng.Empty); var dir = file.Directory.FullName; var ext = file.Extension; if (file.Exists) { int count = 0; ssortingng added; do { count++; added = "(" + count + ")"; } while (File.Exists(dir + "\\" + filename + " " + added + ext)); filename += " " + added; } return (dir + filename + ext); }
Je cherchais une solution qui déplacerait un fichier et assurez-vous que si le nom du fichier de destination n’est pas déjà pris. Il suivrait la même logique que Windows et appendait un numéro, entre parenthèses après le fichier en double.
La première réponse, grâce à @ cadrell0, m’a permis d’arriver à la solution suivante:
/// /// Generates full file path for a file that is to be moved to a destinationFolderDir. /// /// This method takes into account the possiblity of the file already existing, /// and will append number surrounded with brackets to the file name. /// /// Eg if D:\DestinationDir contains file name file.txt, /// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt /// /// /// Eg D:\DestinationDir /// D:\Source\file.txt /// public ssortingng GetFullFilePathWithDuplicatesTakenInMind(ssortingng destinationFolderDir, ssortingng fileToMoveFullPath) { ssortingng destinationPathWithDuplicatesTakenInMind; ssortingng fileNameWithExtension = Path.GetFileName(fileToMoveFullPath); ssortingng fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath); ssortingng fileNameExtension = Path.GetExtension(fileToMoveFullPath); destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension); int count = 0; while (File.Exists(destinationPathWithDuplicatesTakenInMind)) { destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}"); count = count + 1; // sorry, not a fan of the ++ operator. } return destinationPathWithDuplicatesTakenInMind; }
Vous pouvez déclarer un Dictionary
pour conserver le nombre de fois que chaque nom de fichier racine a été enregistré. Après cela, sur votre méthode Save
, augmentez simplement le compteur et ajoutez-le au nom du fichier de base:
var key = fileName.ToLower(); ssortingng newFileName; if(!_dictionary.ContainsKey(key)) { newFileName = fileName; _dictionary.Add(key,0); } else { _dictionary[key]++; newFileName = Ssortingng.Format("{0}({1})", fileName, _dictionary[key]) }
De cette façon, vous aurez un compteur pour chaque nom de fichier distinct: AAA (1), AAA (2); BBB (1) …
Ça marche très bien maintenant. merci les gars pour les réponses ..
ssortingng[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); ssortingng tempFileName = fileName; int count = 1; while (allFiles.Contains(tempFileName )) { tempFileName = Ssortingng.Format("{0} ({1})", fileName, count++); } output = Path.Combine(folderPath, tempFileName ); ssortingng fullPath=output + ".xml";
int count= 0;
fichier est le nom du fichier
while (File.Exists(fullpathwithfilename)) //this will check for existence of file { // below line names new file from file.xls to file1.xls fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls"); count++; }
En ce qui concerne le commentaire de Giuseppe sur la manière dont Windows renomme les fichiers, j’ai travaillé sur une version qui trouve tout index existant (2) dans le nom du fichier et renomme le fichier selon Windows en conséquence. La sourceFileName est supposée être valide et l’utilisateur est supposé avoir des droits en écriture sur le dossier de destination à ce stade:
using System.IO; using System.Text.RegularExpressions; private void RenameDiskFileToMSUnique(ssortingng sourceFileName) { ssortingng destFileName = ""; long n = 1; // ensure the full path is qualified if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); } ssortingng filepath = Path.GetDirectoryName(sourceFileName); ssortingng fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName); ssortingng fileNameSuffix = ""; ssortingng fileNameExt = Path.GetExtension(sourceFileName); // if the name includes the text "(0-9)" then we have a filename, instance number and suffix Regex r = new Regex(@"\(\d+\)"); Match match = r.Match(fileNameWOExt); if (match.Success) // the pattern (0-9) was found { // text after the match if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix { fileNameSuffix = fileNameWOExt.Subssortingng(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length)); fileNameWOExt = fileNameWOExt.Subssortingng(0, match.Index); } else // remove the format at the end { fileNameWOExt = fileNameWOExt.Subssortingng(0, fileNameWOExt.Length - match.Length); } // increment the numeric in the name n = Convert.ToInt64(match.Value.Subssortingng(1, match.Length - 2)) + 1; } // format variation: indexed text retains the original layout, new suffixed text inserts a space! do { if (match.Success) // the text was already indexed { if (fileNameSuffix.Length > 0) { destFileName = Path.Combine(filepath, Ssortingng.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt)); } else { destFileName = Path.Combine(filepath, Ssortingng.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt)); } } else // we are adding a new index { destFileName = Path.Combine(filepath, Ssortingng.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt)); } } while (File.Exists(destFileName)); File.Copy(sourceFileName, destFileName); }