Mudar o nome de um ficheiro Em C#

Como posso mudar o nome de um ficheiro com o C#?

 505
Author: Default, 2010-07-10

14 answers

Dê uma vista de olhos em System. IO. File. Move , "move" o ficheiro para um nome novo.

System.IO.File.Move("oldfilename", "newfilename");
 772
Author: Chris Taylor, 2018-09-05 14:01:08
System.IO.File.Move(oldNameFullPath, newNameFullPath);
 110
Author: Aleksandar Vucetic, 2010-07-10 12:00:50

Pode usar File.Move para o fazer.

 37
Author: Franci Penov, 2010-07-10 11:11:23
No ficheiro.Método de mover, isto não irá sobrepor o ficheiro se já existir. E abrirá uma excepção. Então precisamos verificar se o arquivo existe ou não.
/* 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 rodeá-la com uma captura para evitar uma excepção.
 37
Author: Mohamed Alikhan, 2016-06-12 14:49:18

Basta adicionar:

namespace System.IO
{
    public static class ExtendedMethod
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
        }
    }
}
E depois...
FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
 23
Author: Nogro, 2016-06-12 14:49:35
  1. Primeira solução

    Evite as soluções System.IO.File.Move colocadas aqui (incluindo a resposta marcada). Falha nas redes. No entanto, o padrão copy / delete funciona localmente e através de redes. Siga uma das soluções de movimento, mas substitua-a por Copy. Então usa o ficheiro.Apagar para apagar o ficheiro original.

    Você pode criar um método de renomeação para simplificá-lo.

  2. Facilidade de Utilização

    Usar o conjunto VB em C#. Adicionar referência a Base.VisualBasic

    Depois mudar o nome do ficheiro:

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

    Ambos são cordas. Note que o myfile tem o caminho completo. o newName não. Por exemplo:
    a = "C:\whatever\a.txt";
    b = "b.txt";
    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
    

    A pasta C:\whatever\ irá agora conter b.txt.

 18
Author: Ray, 2016-06-12 14:54:41

Pode copiá-lo como um ficheiro novo e depois apagar o antigo usando a classe System.IO.File:

if (File.Exists(oldName))
{
    File.Copy(oldName, newName, true);
    File.Delete(oldName);
}
 13
Author: Zaki Choudhury, 2016-06-12 14:55:31

Nota: neste código de exemplo, abrimos um directório e procuramos por ficheiros PDF com parêntesis abertos e fechados em nome do ficheiro. Você pode verificar e substituir qualquer personagem no nome que você gosta ou apenas especificar um nome novo inteiro usando funções de substituição.

Existem outras formas de trabalhar a partir deste código para fazer renomeações mais elaboradas, mas a minha principal intenção era mostrar como usar o arquivo.Mover para fazer uma mudança de nome em lote. Isto funcionou contra 335 ficheiros PDF em 180 directórios quando o corri no meu portátil. Este é o impulso do Código do momento e há maneiras mais elaboradas de fazê-lo.

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();
        }
    }
}
 5
Author: MicRoc, 2016-06-12 14:48:15

Utilizar:

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);
 4
Author: Avinash Singh, 2016-06-12 14:51:02
Com sorte! vai ser útil para ti. :)
  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);
        }
    }

Como usar este código ?

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);
        }
    }
 2
Author: , 2016-09-22 04:54:40

O movimento está a fazer o mesmo = copiar e apagar o antigo.

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now));
 1
Author: Nalan Madheswaran, 2014-11-04 06:00:46

No meu caso, quero que o nome do ficheiro renomeado seja único, por isso adiciono um carimbo datetime ao nome. Desta forma, o nome do ficheiro do registo 'velho' é sempre Único:

   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"))));
                }
            }
 1
Author: real_yggdrasil, 2017-11-14 08:55:51
Não consegui encontrar uma abordagem que me agrade, por isso proponho a minha versão. É claro que precisa de entrada, tratamento de erros.
public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}
 0
Author: valentasm, 2018-08-13 17:59:05

Quando o C# não tem nenhuma funcionalidade, Eu uso C++ ou C:

public partial class Program
{
    [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
    public static extern int rename(
            [MarshalAs(UnmanagedType.LPStr)]
            string oldpath,
            [MarshalAs(UnmanagedType.LPStr)]
            string newpath);

    static void FileRename()
    {
        while (true)
        {
            Console.Clear();
            Console.Write("Enter a folder name: ");
            string dir = Console.ReadLine().Trim('\\') + "\\";
            if (string.IsNullOrWhiteSpace(dir))
                break;
            if (!Directory.Exists(dir))
            {
                Console.WriteLine("{0} does not exist", dir);
                continue;
            }
            string[] files = Directory.GetFiles(dir, "*.mp3");

            for (int i = 0; i < files.Length; i++)
            {
                string oldName = Path.GetFileName(files[i]);
                int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
                if (pos == 0)
                    continue;

                string newName = oldName.Substring(pos);
                int res = rename(files[i], dir + newName);
            }
        }
        Console.WriteLine("\n\t\tPress any key to go to main menu\n");
        Console.ReadKey(true);
    }
}
 -11
Author: Alexander Chernosvitov, 2016-06-12 14:44:50