Hernoem een bestand in C#

Hoe hernoem ik een bestand met C#?


Antwoord 1, autoriteit 100%

Bekijk System.IO.File. Verplaats, “verplaats” het bestand naar een nieuwe naam.

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

Antwoord 2, autoriteit 13%

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

Antwoord 3, autoriteit 5%

In de File.Move-methode zal dit het bestand niet overschrijven als het al bestaat. En het zal een uitzondering veroorzaken.

We moeten dus controleren of het bestand bestaat of niet.

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

Of omring het met een try-catch om een uitzondering te voorkomen.


Antwoord 4, autoriteit 4%

U kunt File.Moveom het te doen.


Antwoord 5, autoriteit 3%

Voeg toe:

namespace System.IO
{
    public static class FileInfoExtensions
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
        }
    }
}

En dan…

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

6

U kunt het kopiëren als een nieuw bestand en vervolgens de oude verwijderen met behulp van de System.IO.Fileclass:

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

7

Opmerking: In deze voorbeeldcode openen we een map en zoeken naar PDF-bestanden met open en gesloten haakjes in de naam van het bestand. U kunt een teken in de naam van de naam controleren en vervangen of gewoon een geheel nieuwe naam opgeven met behulp van vervangingsfuncties.

Er zijn andere manieren om met deze code te werken om uitgebreidere hernoemingen uit te voeren, maar mijn belangrijkste bedoeling was om te laten zien hoe File.Move te gebruiken om een batchhernoeming uit te voeren. Dit werkte tegen 335 PDF-bestanden in 180 mappen toen ik het op mijn laptop uitvoerde. Dit is een spontane code en er zijn meer uitgebreide manieren om dit te doen.

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

Antwoord 8

Gebruik:

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

Antwoord 9

Gebruik:

public static class FileInfoExtensions
{
    /// <summary>
    /// Behavior when a new filename exists.
    /// </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);
    }
}

Hoe deze code te gebruiken

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

Antwoord 10

Ik kon geen aanpak vinden die bij mij past, dus stel ik mijn versie voor. Natuurlijk heeft het invoer en foutafhandeling nodig.

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

Antwoord 11

Geen van de antwoorden vermeldt het schrijven van een unit-testable oplossing. Je zou System.IO.Abstractionskunnen gebruiken, omdat het een testbare wrapper rond FileSystem-bewerkingen biedt, waarmee je nepbestandssysteemobjecten kunt maken en eenheidstests kunt schrijven.

using System.IO.Abstractions;
IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));

Het is getest en het is werkende code om een bestand te hernoemen.


Antwoord 12

In mijn geval wil ik dat de naam van het hernoemde bestand uniek is, dus voeg ik een datum-tijdstempel toe aan de naam. Op deze manier is de bestandsnaam van de ‘oude’ log altijd uniek:

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

Antwoord 13

Verplaatsen doet hetzelfde = kopieeren verwijderoude.

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

Antwoord 14

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

Antwoord 15

Ik ben een geval tegengekomen waarin ik het bestand in de gebeurtenishandler moest hernoemen, wat leidde tot elke bestandswijziging, inclusief hernoemen, en om het hernoemen van het bestand voor altijd over te slaan moest ik het hernoemen, met:

p>

  1. Een kopie maken
  2. Het origineel verwijderen
File.Copy(fileFullPath, destFileName); // Both have the format of "D:\..\..\myFile.ext"
Thread.Sleep(100); // Wait for the OS to unfocus the file
File.Delete(fileFullPath);

Antwoord 16

private static void Rename_File(string FileFullPath, string NewName) // nes name without directory actualy you can simply rename with fileinfo.MoveTo(Fullpathwithnameandextension);
        {
            FileInfo fileInfo = new FileInfo(FileFullPath);
            string DirectoryRoot = Directory.GetParent(FileFullPath).FullName;
            string filecreator = FileFullPath.Substring(DirectoryRoot.Length,FileFullPath.Length-DirectoryRoot.Length);
            filecreator = DirectoryRoot + NewName;
            try
            {
                fileInfo.MoveTo(filecreator);
            }
            catch(Exception ex)
            {
                Console.WriteLine(filecreator);
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
    enter code here
            // string FileDirectory = Directory.GetDirectoryRoot()
        }

Antwoord 17

Gebruik:

int rename(const char * oldname, const char * newname);

De functie Rename () wordt gedefinieerd in het headerbestand STDIO.H . Het hernoemt een bestand of map van OldName naar NEWNAME . De wijziging van de hernoemen is hetzelfde als verplaatsen, vandaar dat u deze functie ook kunt gebruiken om een ​​bestand te verplaatsen.


18

Wanneer C # geen functie heeft, gebruik ik C++ of 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);
    }
}

Other episodes