renombrar filesystem files copiar archivo c# file rename

copiar - filesystem.rename c#



Renombrar un archivo en C# (14)

¿Cómo cambio el nombre de un archivo usando C #?


¡Ojalá! Te será de ayuda. :)

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); } }

¿Cómo utilizar 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); } }


  1. Primera solucion

    Evite las soluciones System.IO.File.Move publicadas aquí (se incluye la respuesta marcada). Falla sobre las redes. Sin embargo, copiar / eliminar patrón funciona localmente y en redes. Siga una de las soluciones de movimiento, pero sustitúyala por Copiar. Luego use File.Delete para eliminar el archivo original.

    Puedes crear un método Renombrar para simplificarlo.

  2. Facilidad de uso

    Utilice el conjunto VB en C #. Añadir referencia a Microsoft.VisualBasic

    Luego para renombrar el archivo:

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

    Ambos son cuerdas. Tenga en cuenta que myfile tiene la ruta completa. newName no lo hace. Por ejemplo:

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

    La carpeta C:/whatever/ ahora contendrá b.txt .


Cuando C # no tiene alguna característica, uso C ++ o 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); } }


Eche un vistazo a System.IO.File.Move , "mueva" el archivo a un nuevo nombre.

System.IO.File.Move("oldfilename", "newfilename");


En el método File.Move, esto no sobrescribirá el archivo si ya existe. Y lanzará una excepción.

Así que tenemos que comprobar si el archivo existe o no.

/* 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

O rodearlo con un retén de prueba para evitar una excepción.


En mi caso, quiero que el nombre del archivo renombrado sea único, así que agrego un sello de fecha y hora al nombre. De esta manera, el nombre de archivo del registro ''antiguo'' es siempre ú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")))); } }


Mover es hacer lo mismo = Copiar y eliminar el anterior.

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


No pude encontrar el enfoque que más me convenga, así que propongo mi versión. Por supuesto necesita entrada, manejo de errores.

public void Rename(string filePath, string newFileName) { var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath)); System.IO.File.Move(filePath, newFilePath); }


Puede copiarlo como un archivo nuevo y luego eliminar el anterior usando la clase System.IO.File :

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



Solo agrega:

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

Y entonces...

FileInfo file = new FileInfo("c:/test.txt"); file.Rename("test2.txt");


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


NOTA: En este código de ejemplo, abrimos un directorio y buscamos archivos PDF con paréntesis abiertos y cerrados en el nombre del archivo. Puede verificar y reemplazar cualquier carácter en el nombre que desee o simplemente especificar un nombre completamente nuevo utilizando las funciones de reemplazo.

Hay otras formas de trabajar con este código para hacer cambios de nombre más elaborados, pero mi intención principal era mostrar cómo usar File.Move para hacer un cambio de nombre por lotes. Esto funcionó contra 335 archivos PDF en 180 directorios cuando lo ejecuté en mi computadora portátil. Este es el código del momento y hay formas más elaboradas de hacerlo.

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(); } } }


System.IO.File.Move(oldNameFullPath, newNameFullPath);