2010-07-10 92 views
451

如何使用C#重命名文件?以C#重命名文件

+0

我讨厌补充一点,有一个问题在这里所有的解决方案在这里,特别是如果你做比较,并正在从一个位置的文件到另一个(目录以及文件名),因为你应该知道一个卷可能是一个交汇点......所以如果newname是q:\ SomeJunctionDirectory \ hello.txt并且旧名称是c:\ TargetOfJunctionPoint \ hello。 TXT ...文件是相同的,但名称不是。 – 2016-10-14 01:26:18

回答

688

看看System.IO.File.Move,将文件“移动”到一个新名称。

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

当文件名仅在字母大小写方面不同时,此解决方案不起作用。例如file.txt和File.txt – SepehrM 2014-07-06 20:31:19

+2

@SepehrM,我只是再次检查,它在我的Windows 8.1机器上正常工作。 – 2014-07-07 01:57:19

+0

我不知道为什么发生这种情况,但看看这些帖子:http://stackoverflow.com/questions/8152731/file-or-folder-rename-to-lower-case-in-c-sharp-using -directoryinfo-fileinfo-move和http://www.codeproject.com/Tips/365773/Rename-a-directory-or-file-name-to-lower-case-with – SepehrM 2014-07-07 06:43:55

100
System.IO.File.Move(oldNameFullPath, newNameFullPath); 
-11

另外,在C#所没有的一些功能,我用C++或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); 
    } 
} 
+18

C#完全有能力重命名文件。 – 2012-10-26 04:53:26

+67

我无言以对 – 2013-05-10 19:17:48

4

注:在这个例子的代码,我们打开一个目录,搜索与打开的PDF文件,并在关闭括号文件的名称。您可以检查并替换您喜欢的名称中的任何字符,或者使用替换功能指定一个全新的名称。

还有其他的方法可以从这段代码中做更多详细的重命名,但我的主要目的是展示如何使用File.Move来执行批量重命名。当我在笔记本上运行它时,这对180个目录中的335个PDF文件起作用。这是时代代码的激励,并且有更多精细的方法来实现它。

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

这完全不是问题所在,关于3年前刚刚回答的问题。 – Nyerguds 2013-11-19 11:33:36

+1

这是一个有效的例子。夸大其辞,可能并不重要。 +1 – Adam 2013-11-27 09:11:15

+1

@Adam:这是一个非常具体的实现,就是三年前已经给出的答案,这个问题不是关于任何具体实现的问题。看不出这是如何具有建设性的。 – Nyerguds 2013-12-05 10:52:38

34

在File.Move方法中,如果文件已存在,则不覆盖文件。它会抛出一个异常。

所以我们需要检查文件是否存在。

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

或者用try catch包围它以避免异常。

+11

对这种方法非常小心......如果你的目标目录和你的源目录是相同的,而“newname”实际上是“oldFileName”的区分大小写的版本,你将在你有机会移动你的文件之前删除它。 – 2016-10-14 01:16:41

+0

您也不能仅仅检查字符串是否相等,因为有多种方式来表示单个文件路径。 – 2017-12-13 22:03:11

23

只需添加:

namespace System.IO 
{ 
    public static class ExtendedMethod 
    { 
     public static void Rename(this FileInfo fileInfo, string newName) 
     { 
      fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName); 
     } 
    } 
} 

然后......

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

如果一个子文件夹已存在,称为newName – 2014-12-15 20:34:19

+0

...“\\”+ newName + fileInfo.Extension – mac10688 2016-02-15 18:22:35

+10

eww ...这将不起作用...使用Path.Combine()而不是汇编文件。 – 2016-10-14 01:19:09

4

用途:

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

如果你打算这样做,我会建议在做任何事之前检查'oldFilePath'是否存在......否则你会无缘无故地删除'newFilePath'。 – 2014-07-09 19:18:45

+0

这是否甚至编译('使用System.IO;')? – 2016-06-12 14:51:56

18
  1. 首先解决

    Avoi d System.IO.File.Move在这里发布的解决方案(标记为答案)。 它通过网络故障。但是,复制/删除模式可以在本地和网络上使用。按照其中一个移动解决方案进行操作,但将其替换为Copy。然后使用File.Delete删除原始文件。

    您可以创建一个Rename方法来简化它。

  2. 易于使用

    的使用VB组件在C#。 添加引用Microsoft.VisualBasic程序

    然后重命名的文件:

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

    两者都是字符串。请注意,myfile具有完整路径。 newName不。 例如:

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

    C:\whatever\文件夹现在将包含b.txt

+7

只是让你知道,Microsoft.VisualBasic.FileIO.FileSystem.RenameFile调用File.Move。其他感谢正常化原始文件,并对参数进行一些额外的错误检查。文件存在,文件名不为空等,然后调用File.Move。 – 2014-07-07 02:07:03

+0

除非Copy()复制所有文件流,我认为它没有,我会远离使用删除/复制。我假设Move(),至少在停留在同一个文件系统上时,只是重命名,因此所有文件流都将保留。 – nickdu 2016-12-01 00:54:25

10

你可以将它复制为一个新的文件,然后删除使用System.IO.File类旧:

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

注意:读取此内容的任何人:这是一种反模式,该文件可能会被另一个进程或操作系统删除或重命名,检查它是否存在以及是否调用复制。你需要改用try catch。 – user9993 2016-04-20 15:31:36

+0

如果卷是相同的,这也是I/O的巨大浪费,因为移动实际上会在目录信息级别进行重命名。 – 2016-10-14 01:20:57

1

移动在做同样=复制和删除旧的。

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

诚然,如果你关心的只是最终结果。在内部,并非如此。 – Michael 2015-12-18 23:08:12

+0

不,移动肯定不会复制和删除。 – 2017-03-07 09:29:17

1

希望!这对你有帮助。 :)

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

如何使用此代码?

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

在我的情况,我想重命名的文件名是唯一的,所以我添加了一个日期时间戳的名字。这样一来,“旧”的日志的文件名始终是唯一的:

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