How to rename a file and directory in C#?

I am working with files and directory in C#, so I would like to know how can I rename a file and directory in C#? I would like to rename file first and then in some cases would have to rename directory also.

I see there is File.Move Method, but is there any other method or way to rename a file and what about Directory, how to rename directory?

Asked by:- bhanu
: 71 At:- 4/21/2021 11:43:07 AM
C# c# rename file c# rename directory

1 Answers
profileImage Answered by:- vikas_jk

Yes, you can use File.Move, similarly you can use Directory.Move for renaming directory, here is the sample code for both

using System.IO;

namespace RenameFile
    class Program
        static void Main(string[] args)
            var SourceName = @"E:\SampleDir\SampleFile.txt";
            var DestinationName= @"E:\SampleDir\SampleFileNew.txt";

            File.Move(SourceName, DestinationName); //change file name

            var source = @"E:\SampleDir";
            var destination = @"E:\SampleDirNew";
            Directory.Move(source, destination); //change directory name


When executed the above code, I was able to see changes in Directory and file name, here is output


You can also check about File I/O in C# and How to get all files inside folder using C# easily

At:- 4/21/2021 3:02:32 PM
thanks for the answer, it was helpful 0
By : bhanu - at :- 4/21/2021 3:05:44 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use