用C#重命名文件

Gol*_*old 577 c# rename file

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

Chr*_*lor 903

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

System.IO.File.Move("oldfilename", "newfilename");
Run Code Online (Sandbox Code Playgroud)

  • 当文件名仅在字母大小写不同时,此解决方案不起作用.例如file.txt和File.txt (10认同)
  • @Michael,文件系统不区分大小写,但它确实将文件名存储在用户输入的原始大小写中.在SepehrM的案例中,他试图改变一个文件的情况,由于某种原因,该文件无效.不区分大小写的匹配正在起作用.HTH (3认同)
  • 仅供大家参考,如果区分大小写的文件落入旧的 8.3 限制,您只会遇到不更改的问题。 (3认同)
  • @SepehrM,我只是仔细检查过,它在我的Windows 8.1机器上运行正常. (2认同)
  • @SepehrM Windows 文件系统名称不区分大小写。File.txt 和 file.txt 被视为相同的文件名。因此,当您说解决方案不起作用时,我不清楚。你究竟在做什么,这不起作用? (2认同)

Ale*_*tic 124

System.IO.File.Move(oldNameFullPath, newNameFullPath);
Run Code Online (Sandbox Code Playgroud)


Moh*_*han 42

在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
Run Code Online (Sandbox Code Playgroud)

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

  • 请小心这种方法...如果您的目标目录和源目录相同,并且"newname"实际上是"oldFileName"的区分大小写的版本,您将在有机会移动文件之前删除. (17认同)
  • File.Move 现在有一个重载方法,允许您覆盖文件 - File.Move(oldPath, newPath, true) (3认同)
  • 您也不能只检查字符串是否相等,因为有多种表示单个文件路径的方法。 (2认同)

Fra*_*nov 39

你可以File.Move用来做.


Nog*_*gro 32

只需添加:

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

然后...

FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
Run Code Online (Sandbox Code Playgroud)

  • eww ...使用Path.Combine()而不是汇编文件. (23认同)

小智 20

  1. 第一解决方案

    避免System.IO.File.Move在此处发布解决方案(包括标记答案).它失败了网络.但是,复制/删除模式在本地和网络上工作.请遵循其中一个移动解决方案,但请将其替换为Copy.然后使用File.Delete删除原始文件.

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

  2. 便于使用

    在C#中使用VB程序集.添加对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);
    
    Run Code Online (Sandbox Code Playgroud)

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

  • 您知道,Microsoft.VisualBasic.FileIO.FileSystem.RenameFile调用File.Move.其他感谢规范原始文件并对参数进行一些额外的错误检查,即.文件存在,文件名不为空等,然后调用File.Move. (8认同)

Zak*_*ury 16

您可以将其复制为新文件,然后使用System.IO.File该类删除旧文件:

if (File.Exists(oldName))
{
    File.Copy(oldName, newName, true);
    File.Delete(oldName);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意阅读此内容的任何人:这是一个反模式,该文件可能被其他进程或操作系统在检查(如果存在)和您对Copy的调用之间删除或重命名.你需要使用try catch. (4认同)

Maj*_*man 13

public void RenameFile(string filePath, string newName)
{
    FileInfo fileInfo = new FileInfo(filePath);
    fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*Roc 6

注意:在此示例代码中,我们打开一个目录,并在文件名中搜索带有左括号和右括号的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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 那是......完全不在这一点上,在一个问题上完全回答了3年前的观点. (3认同)
  • 这是一个有效的例子。过度杀伤也许但并非没有意义。+1 (2认同)

Avi*_*ngh 6

使用:

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);
Run Code Online (Sandbox Code Playgroud)

  • 如果你打算这样做,我建议在做任何事之前检查'oldFilePath'是否存在......否则你会毫无理由地删除'newFilePath'. (4认同)

小智 6

用:

public static class FileInfoExtensions
{
    /// <summary>
    /// Behavior when a new filename exists.
    /// </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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用此代码

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


val*_*asm 6

我找不到适合我的方法,所以我提出了我的版本。当然,它需要输入和错误处理。

public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}
Run Code Online (Sandbox Code Playgroud)


Adi*_*aza 5

没有一个答案提到编写一个单元可测试的解决方案。您可以使用System.IO.Abstractions它,因为它提供了一个围绕 FileSystem 操作的可测试包装器,您可以使用它来创建模拟文件系统对象并编写单元测试。

using System.IO.Abstractions;

IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));
Run Code Online (Sandbox Code Playgroud)

它已经过测试,并且是重命名文件的工作代码。