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
0
: 6548 At:- 4/21/2021 11:43:07 AM
C# c# rename file c# rename directory







2 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

rename-file-or-directory-csharp-min.png

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

2
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


profileImage Answered by:- pika

If you want to rename all files in a directory in C#

DirectoryInfo d = new DirectoryInfo(@"D:\SampleDirectory");
FileInfo[] infos = d.GetFiles(); // get all files in directory
foreach(FileInfo f in infos)
{
    // loop files and use File.Move to update name
    File.Move(f.FullName, f.FullName.Replace("test","WithNewTest"));
}

We are looping each file and renaming it using File.Move in C#

0
At:- 6/3/2022 7:38:28 AM






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

Full Name *

Email *




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