Rename a file in C#

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

How do I rename a file using C#?

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

    Hopefully! it will be helpful for you. :)

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

    How to use this 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);
            }
        }
    
    0 讨论(0)
  • I've encountered a case when I had to rename the file inside the event handler, which was triggering for any file change, including rename, and to skip forever renaming of the file I had to rename it, with:

    1. Making its copy
    2. Removing the original
    File.Copy(fileFullPath, destFileName); // both has the format of "D:\..\..\myFile.ext"
    Thread.Sleep(100); // wait OS to unfocus the file 
    File.Delete(fileFullPath);
    

    Just in case if someone, will have such scenario ;)

    0 讨论(0)
  • int rename(const char * oldname, const char * newname);
    

    rename() function is defined in stdio.h header file. It renames a file or directory from oldname to newname. The rename operation is same as move, hence you can also use this function to move a file.

    0 讨论(0)
  • 2020-11-22 15:43

    Take a look at System.IO.File.Move, "move" the file to a new name.

    System.IO.File.Move("oldfilename", "newfilename");
    
    0 讨论(0)
  • 2020-11-22 15:44

    None of the answers mention writing unit testable solution. You could use System.IO.Abstractions as it provides testable wrapper around FileSystem operations, using which you can create mocked file system objects and write Unit Tests.

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

    Tested and working code to rename a file.

    0 讨论(0)
  • 2020-11-22 15:45
    System.IO.File.Move(oldNameFullPath, newNameFullPath);
    
    0 讨论(0)
提交回复
热议问题