Rename a file in C#

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

How do I rename a file using C#?

18条回答
  •  旧巷少年郎
    2020-11-22 15:44

    None of the answers mention writing unit testable solution. You could use System.IO.Abstractions as it provides testable wrapper around FileSystem operations, using which you can create mocked file system objects and write Unit Tests.

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

    Tested and working code to rename a file.

提交回复
热议问题