我如何重命名一个文件使用c# ?


当前回答

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

using System.IO.Abstractions;

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

它已经过测试,它正在重命名文件的工作代码。

其他回答

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

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. 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.

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

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

添加:

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

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

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