Rename a file in C#

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

How do I rename a file using C#?

18条回答
  •  孤街浪徒
    2020-11-22 15:28

    Just add:

    namespace System.IO
    {
        public static class FileInfoExtensions
        {
            public static void Rename(this FileInfo fileInfo, string newName)
            {
                fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
            }
        }
    }
    

    And then...

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

提交回复
热议问题