Rename a file in C#

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

How do I rename a file using C#?

18条回答
  •  庸人自扰
    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);               
            }
        }
    

提交回复
热议问题