web-dev-qa-db-fra.com

Renommer un fichier en C #

Comment renommer un fichier en C #?

565
Gold

Jetez un oeil à System.IO.File.Move , "déplacez" le fichier vers un nouveau nom.

System.IO.File.Move("oldfilename", "newfilename");
875
Chris Taylor
System.IO.File.Move(oldNameFullPath, newNameFullPath);
123
Aleksandar Vucetic

Dans la méthode File.Move, cela ne remplacera pas le fichier s'il existe déjà. Et il va jeter une exception.

Nous devons donc vérifier si le fichier existe ou non.

/* Delete the file if exists, else no exception thrown. */

File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName

Ou entourez-le d'un essai pour éviter une exception.

41
Mohamed Alikhan

Vous pouvez utiliser File.Move pour le faire.

39
Franci Penov

Il suffit d'ajouter:

namespace System.IO
{
    public static class ExtendedMethod
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
        }
    }
}

Puis...

FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
31
Nogro
  1. Première solution

    Évitez les solutions System.IO.File.Move affichées ici (réponse marquée incluse). Il échoue sur les réseaux. Toutefois, le modèle de copie/suppression fonctionne localement et sur les réseaux. Suivez l'une des solutions de déplacement, mais remplacez-la par Copier. Ensuite, utilisez File.Delete pour supprimer le fichier d'origine.

    Vous pouvez créer une méthode Rename pour la simplifier.

  2. Facilité d'utilisation

    Utilisez le VB Assembly en C #. Ajouter une référence à Microsoft.VisualBasic

    Ensuite, pour renommer le fichier:

    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);

    Les deux sont des chaînes. Notez que mon fichier a le chemin complet. newName ne le fait pas. Par exemple:

    a = "C:\whatever\a.txt";
    b = "b.txt";
    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
    

    Le dossier C:\whatever\ contient désormais b.txt.

20
Ray

Vous pouvez le copier en tant que nouveau fichier, puis supprimer l'ancien en utilisant la classe System.IO.File:

if (File.Exists(oldName))
{
    File.Copy(oldName, newName, true);
    File.Delete(oldName);
}
15
Zaki Choudhury

NOTE: Dans cet exemple de code, nous ouvrons un répertoire et recherchons les fichiers PDF avec des parenthèses ouvertes et fermées dans le nom du fichier. Vous pouvez vérifier et remplacer n'importe quel caractère du nom de votre choix ou simplement spécifier un nouveau nom à l'aide des fonctions de remplacement.

Il existe d’autres manières de travailler à partir de ce code afin de renommer de manière plus élaborée, mais mon intention principale était de montrer comment utiliser File.Move pour renommer un lot. Cela a fonctionné contre 335 PDF fichiers dans 180 répertoires lorsque je l'ai exécuté sur mon ordinateur portable. C'est le code du moment et il existe des moyens plus élaborés de le faire.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenamer
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");

            int i = 0;

            try
            {
                foreach (var dir in dirnames)
                {
                    var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);

                    DirectoryInfo d = new DirectoryInfo(dir);
                    FileInfo[] finfo = d.GetFiles("*.pdf");

                    foreach (var f in fnames)
                    {
                        i++;
                        Console.WriteLine("The number of the file being renamed is: {0}", i);

                        if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
                        {
                            File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
                        }
                        else
                        {
                            Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
                            foreach (FileInfo fi in finfo)
                            {
                                Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}
6
MicRoc

Utilisation:

using System.IO;

string oldFilePath = @"C:\OldFile.txt"; // Full path of old file
string newFilePath = @"C:\NewFile.txt"; // Full path of new file

if (File.Exists(newFilePath))
{
    File.Delete(newFilePath);
}
File.Move(oldFilePath, newFilePath);
6
Avinash Singh

J'espère! cela vous sera utile. :)

  public static class FileInfoExtensions
    {
        /// <summary>
        /// behavior when new filename is exist.
        /// </summary>
        public enum FileExistBehavior
        {
            /// <summary>
            /// None: throw IOException "The destination file already exists."
            /// </summary>
            None = 0,
            /// <summary>
            /// Replace: replace the file in the destination.
            /// </summary>
            Replace = 1,
            /// <summary>
            /// Skip: skip this file.
            /// </summary>
            Skip = 2,
            /// <summary>
            /// Rename: rename the file. (like a window behavior)
            /// </summary>
            Rename = 3
        }
        /// <summary>
        /// Rename the file.
        /// </summary>
        /// <param name="fileInfo">the target file.</param>
        /// <param name="newFileName">new filename with extension.</param>
        /// <param name="fileExistBehavior">behavior when new filename is exist.</param>
        public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
        {
            string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
            string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
            string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);

            if (System.IO.File.Exists(newFilePath))
            {
                switch (fileExistBehavior)
                {
                    case FileExistBehavior.None:
                        throw new System.IO.IOException("The destination file already exists.");
                    case FileExistBehavior.Replace:
                        System.IO.File.Delete(newFilePath);
                        break;
                    case FileExistBehavior.Rename:
                        int dupplicate_count = 0;
                        string newFileNameWithDupplicateIndex;
                        string newFilePathWithDupplicateIndex;
                        do
                        {
                            dupplicate_count++;
                            newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
                            newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
                        } while (System.IO.File.Exists(newFilePathWithDupplicateIndex));
                        newFilePath = newFilePathWithDupplicateIndex;
                        break;
                    case FileExistBehavior.Skip:
                        return;
                }
            }
            System.IO.File.Move(fileInfo.FullName, newFilePath);
        }
    }

Comment utiliser ce code?

class Program
    {
        static void Main(string[] args)
        {
            string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
            string newFileName = "Foo.txt";

            // full pattern
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
            fileInfo.Rename(newFileName);

            // or short form
            new System.IO.FileInfo(targetFile).Rename(newFileName);
        }
    }
4
user5039044

Déplacer fait de même = Copier et supprimer l'ancien.

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now));
2

Dans mon cas, je veux que le nom du fichier renommé soit unique, alors j’ajoute un tampon datetime au nom. De cette façon, le nom de fichier de l'ancien journal est toujours unique:

   if (File.Exists(clogfile))
            {
                Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
                if (fileSizeInBytes > 5000000)
                {
                    string path = Path.GetFullPath(clogfile);
                    string filename = Path.GetFileNameWithoutExtension(clogfile);
                    System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
                }
            }
2
real_yggdrasil

Je ne trouvais pas l'approche qui me convient, je propose donc ma version. Bien sûr, besoin de saisie, de gestion des erreurs.

public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}
1
valentasm
  public static class ImageRename
    {
        public static void ApplyChanges(string fileUrl,
                                        string temporaryImageName, 
                                        string permanentImageName)
        {               
                var currentFileName = Path.Combine(fileUrl, 
                                                   temporaryImageName);

                if (!File.Exists(currentFileName))
                    throw new FileNotFoundException();

                var extention = Path.GetExtension(temporaryImageName);
                var newFileName = Path.Combine(fileUrl, 
                                            $"{permanentImageName}
                                              {extention}");

                if (File.Exists(newFileName))
                    File.Delete(newFileName);

                File.Move(currentFileName, newFileName);               
        }
    }
1
AminGolmahalle