Thursday, August 13, 2009

How to move the files from one folder to another folder using C#?

Files can be moved from source to destination using System.IO namespace in c#.
This code will move the files from source directory having 1 sub level of directory or not.
string destination = string.Empty;
string source = string.Empty;
destination = Server.MapPath("Destination");
source = Server.MapPath("Source");

//follwing code can used to move the directory files from one folder to
//another
DirectoryInfo dir = new DirectoryInfo(source);
if (dir.Exists)
{
DirectoryInfo[] subDirs = dir.GetDirectories();
if (subDirs.Length > 0)
{
foreach (DirectoryInfo d in subDirs)
{
FileInfo[] files = d.GetFiles();
foreach (FileInfo f in files)
{
f.MoveTo(destination);
}
}
}
else
{
FileInfo[] files = dir.GetFiles();
if (files.Length > 0)
{
foreach (FileInfo f in files)
{
//f.CopyTo(destination);

f.MoveTo(Path.Combine(destination, f.Name));
}
}
else
{
Response.Write("file does not exists");
}
}
}
else
{
Response.Write("Source Directory Does not exists");
}

No comments:

Post a Comment