Rename a file in C#

后端 未结 18 849
北荒
北荒 2020-11-22 15:05

How do I rename a file using C#?

相关标签:
18条回答
  • 2020-11-22 15:27

    Use:

    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);
    
    0 讨论(0)
  • 2020-11-22 15:28

    Just add:

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

    And then...

    FileInfo file = new FileInfo("c:\test.txt");
    file.Rename("test2.txt");
    
    0 讨论(0)
  • 2020-11-22 15:30

    In my case, I want the name of the renamed file to be unique, so I add a date-time stamp to the name. This way, the filename of the 'old' log is always 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"))));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:30

    I couldn't find approach which suits me, so i propose my version. Of course need input, error handling.

    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 讨论(0)
  • 2020-11-22 15:33

    Move is doing the same = Copy and Delete old one.

    File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now));
    
    0 讨论(0)
  • 2020-11-22 15:34

    NOTE: In this example code we open a directory and search for PDF files with open and closed parenthesis in the name of the file. You can check and replace any character in the name you like or just specify a whole new name using replace functions.

    There are other ways to work from this code to do more elaborate renames but my main intention was to show how to use File.Move to do a batch rename. This worked against 335 PDF files in 180 directories when I ran it on my laptop. This is spur of the moment code and there are more elaborate ways to do it.

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题