Moving files from one folder to another


This article explain about how to Moving files from one folder to another with the code snippet in simple way.

The following c# code shows how to move all the files in one folder to another. The program can be customized to move selected files too


DirectoryInfo dir1= new DirectoryInfo("F:Folder1");
DirectoryInfo dir2 = new DirectoryInfo("F:Folder2");

FileInfo[] Folder1Files = dir1.GetFiles();
if(Folder1Files.Length > 0)
{
foreach(FileInfo aFile in Folder1Files)
{
if(File.Exists("F:Folder2" + aFile.Name))
{
File.Delete("F:Folder2" + aFile.Name);
}
aFile.MoveTo("F:Folder2" + aFile.Name);
}
}


Comments

Author: Kapil Dhawan17 Jun 2008 Member Level: Gold   Points : 2

Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code will help lots of guys
Thanks to you
Regards,
Kapil

Author: revathy14 Jul 2009 Member Level: Bronze   Points : 1

hi,
I am getting the below error in the line
FileInfo[] Folder1Files = dir1.GetFiles();
{"Logon failure: unknown user name or bad password.\r\n" }
Please help me to resolve this.

Author: revathy14 Jul 2009 Member Level: Bronze   Points : 0

Thanks a lot.YOur code is very simple and superb.
Its working fine.

Guest Author: Ajay24 Aug 2012

Simple Superb ......nice !!!

Guest Author: Chaitanya11 Sep 2013

Really good article

Guest Author: Flip12 Feb 2014

Dear kapil....
Greetings, your code is very simple and worth but i have complexity that how to select a particular file or group of files (to be specific images) to transfer from one folder to another.
Please Contribute....
Thanks in Advance.

Regards,
F@!Z



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: