How to move all files from one directory to other directory using C# code?
In this article I am going to explain about how to move all files from the one directory to other using C# code. This concept is used in various scenario in our projects.
Description
I am create one method name as MoveFiles, this method is call recursively for sub folders files too. So move all files including sub folder files too using this concept. And then finally after move all files just delete that old directory using C# code itself.Client side
Just I have placed one button control to get command from user.Server side
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string source, destination;
Boolean overwrite=false;
//Mention here your source and destination path
//source mean where you want copy file and destination means where you move to that file
source = "E:\\temp1";
destination = "E:\\temp2";
MoveFiles(source, destination, overwrite);
//Finally delete old folder after copy that files
if (System.IO.Directory.Exists(source))
{
System.IO.Directory.Delete(source);
}
}
private void MoveFiles(string source, string destination, bool overwrite)
{
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(source);
System.IO.DirectoryInfo outputDir = new System.IO.DirectoryInfo(destination);
try
{
if ((inputDir.Exists))
{
if (!(outputDir.Exists))
{
outputDir.Create();
}
//Get Each files and copy
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if ((overwrite))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), true);
}
else
{
if (((System.IO.File.Exists(System.IO.Path.Combine(outputDir.FullName, file.Name))) == false))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), false);
}
}
System.IO.File.Delete(file.FullName);
}
//Sub folder access code
System.IO.DirectoryInfo dir = null;
foreach (System.IO.DirectoryInfo subfolderFile in inputDir.GetDirectories())
{
dir = subfolderFile;
//Destination path
if ((dir.FullName != outputDir.ToString()))
{
MoveFiles(dir.FullName, System.IO.Path.Combine(outputDir.FullName, dir.Name), overwrite);
}
System.IO.Directory.Delete(dir.FullName);
}
}
}
catch (Exception ex)
{
}
}
}Source code:
Client Side: ASP.NET
Code Behind: C#Conclusion
I hope this article is help you to know about Move all files from one to another directory.
tahnk u boss.really helped me...