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?
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
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#
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly