Rename a file in C#

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

How do I rename a file using C#?

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

    You can use File.Move to do it.

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

    When C# doesn't have some feature, I use C++ or 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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:24

    In the File.Move method, this won't overwrite the file if it is already exists. And it will throw an exception.

    So we need to check whether the file exists or not.

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

    Or surround it with a try catch to avoid an exception.

    0 讨论(0)
  • 2020-11-22 15:25
    1. First solution

      Avoid System.IO.File.Move solutions posted here (marked answer included). It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file.

      You can create a Rename method to simplify it.

    2. Ease of use

      Use the VB assembly in C#. Add reference to Microsoft.VisualBasic

      Then to rename the file:

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

      Both are strings. Note that myfile has the full path. newName does not. For example:

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

      The C:\whatever\ folder will now contain b.txt.

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

    You can copy it as a new file and then delete the old one using the System.IO.File class:

    if (File.Exists(oldName))
    {
        File.Copy(oldName, newName, true);
        File.Delete(oldName);
    }
    
    0 讨论(0)
提交回复
热议问题