Excluding a file while copying - c#

I want to copy all files from the current folder to another folder inside that.
but excluding few files which is a .exe file and a .dll file.
this is the code i have right now, this copies every file from current to the other folder. i have searched and got few answers to exclude based on the extensions but that isnt what i was looking for. i want to exclude based on their name so that i can exclude more files later on.
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}

This should work:
HashSet<string> namesToExclude = new HashSet<string>()
{
"bla.dll",
"blubb.exe"
};
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
{
if (!namesToExclude.Contains(Path.GetFileName(newPath)))
{
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}
}
}
Oh and as a sidenote, your code will not copy if there are only directories and no files inside the root directory, you might want to check for directories as well. And subdirectories will be a problem as well. You could use recursion to fix this.

Try, that should work:
async Task<void> Copy(List<string> ExcludedNamesWithoutExtensions)
{
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
{
bool CanCopy = true;
string[] array = newPath.Split('\\')[newPath.Split('\\').Length - 1].Split('.');
string name = array[array.Length - 1];
foreach (string s in ExcludedNamesWithoutExtensions)
{
if (name != s)
{
CanCopy = false;
break;
}
}
if (CanCopy)
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}
}
}

Related

Stepping through directories and sub-directories

I have code that steps through a main directory and all the sub directories. The images in each sub directories needs to be renamed as per the folder it is ins name.
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\\Batch002-190227010418829\PPA14431564096\File1.png
should rename to
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\Batch002-190227010418829\PPA14431564096\PPA14431564096.png
I can see the code is stepping through every thing but the image isn't beeing renamed and I can't see where I went wrong
while(isTrue)
{
try
{
//write your code here
string filename1 = "1.tif";
string newFileName = "allen.tif";
string[] rootFolder = Directory.GetDirectories(#"C:\Users\alle\Desktop\BillingCopy");
foreach(string dir in rootFolder)
{
string[] subDir1 = Directory.GetDirectories(dir);
foreach(string subDir in subDir1)
{
string[] batchDirList = Directory.GetDirectories(subDir);
foreach(string batchDir in batchDirList)
{
string[] waybillNumberDir = Directory.GetDirectories(batchDir);
foreach(string hawbDir in waybillNumberDir)
{
string waybillNumber = Path.GetDirectoryName(hawbDir);
string[] getFileimages = Directory.GetFiles(hawbDir);
foreach(string imgInDir in getFileimages)
{
File.Copy(imgInDir, Path.Combine(#"C:\Users\alle\Desktop\Copy", string.Format("{0}.{1}", waybillNumber, Path.GetExtension(imgInDir))));
}
}
}
}
}
File.Copy(Path.Combine("source file", filename1), Path.Combine("dest path",
string.Format("{0}{1}", Path.GetFileNameWithoutExtension(newFileName), Path.GetExtension(newFileName))), true);
}
catch { }
}
When querying you can try using Linq to obtain the required data:
// All *.png files in all subdirectories
string rootDir = #"C:\Users\alle\Desktop\BillingCopy";
var agenda = Directory
.EnumerateFiles(rootDir, "*.png", SearchOption.AllDirectories)
.Select(file => new {
oldName = file,
newName = Path.Combine(
Path.GetDirectoryName(file),
new DirectoryInfo(Path.GetDirectoryName(file)).Name + Path.GetExtension(file))
})
.ToArray();
Then we can move (not copy) the files:
foreach (var item in agenda)
File.Move(item.oldName, item.newName);

Copy specific Folder with 3 Files only to New Folder

One Question about coding (Visual Studio C# WindowsformApplication) There have Two folder: (Source and Target) and I build 1 button "Copy".
In "Source" folder have random folders such as "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] .txt files. What is the coding if I only want to copy all "201904**" folders with [3] .txt files inside it to "Target" folder? Here is my code for now.
Code
** private void button1_Click
{
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("success");
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}**
I expect after I click a button,
output is automatically copy all folders Name Start With "201904**" with [3] text files inside from "Source" folder to "target" folder.
I reckon you can search the directory with names directly using linq and can copy the sub folders/files inside it like below. It will give you the flexibility of filtering folders/files/skipping/taking n folders/files
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
string searchText = "201904";
string extension = "txt";
IEnumerable<string> dirs = Directory.EnumerateDirectories(FROM_DIR, "*", SearchOption.AllDirectories)
.Where(dirPath=>Path.GetFileName(dirPath.TrimEnd(Path.DirectorySeparatorChar)).StartsWith(searchText));
foreach (string dir in dirs)
{
string destDirPath = dir.Replace(FROM_DIR, TO_DIR);
if (!Directory.Exists(destDirPath))
Directory.CreateDirectory(destDirPath);
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.EnumerateFiles(dir, string.format("*.{0}",extension),
SearchOption.AllDirectories))// Here you can skip/take n files if u need
File.Copy(newPath, newPath.Replace(FROM_DIR, TO_DIR), true);
}
Have tested with sub folders and files inside source folder as well. Hope it helps.

How to copy selected folders, subfolders and files from openFileDialog in c#

I have a function that is suposed to copy all folders, subfolders files selected from openFileDialog from a location to another:
I've made this function to copy all the selected paths:
public void CopiarFicheiros(string CopyTo, List<string> FilesToCopy )
{
foreach (var item in FilesToCopy)
{
string DirectoryName = Path.GetDirectoryName(item);
string Copy = Path.Combine(CopyTo, DirectoryName);
if (Directory.Exists(Copy) && DirectoryName.ToLower() != "newclient" && DirectoryName.ToLower() != "newservice")
{
Directory.CreateDirectory(Copy);
File.Copy(item, Copy + #"\" + Path.GetFileName(item), true);
}
else File.Copy(item, CopyTo + #"\" + Path.GetFileName(item), true);
}
}
The logic is full of flaws and I'm running out of time and can't seem to find a proper solution to this.
This is how I get the selected files and folders from the dialog:
private List<string> GetFiles()
{
var Files = new List<string>();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string sFileName = openFileDialog.FileName;
string[] arrAllFiles = openFileDialog.FileNames;
Files = arrAllFiles.ToList();
}
return Files;
}
Does anyone have a better solution or a clue to what I need to change to successfully do this?
Any help is highly appreciated, thank you
Don't use OpenFileDialog to choose the folder. As the name suggests, it not made for that task. You want the FolderBrowserDialog class for this task.
How to: Copy Directories:
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", #".\temp", true);
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}

Copy directory with all files and folders

I'm trying to copy one directory to another path.
I found this method, but it does not copy the directory, only the sub-directories and files inside it:
string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");
foreach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));
}
foreach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);
}
How I can get the "Program" folder in output with all files and sub-folders?
If you adjust the output path before you start copying, it should work:
string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");
folderDialog.SelectedPath = Path.Combine(folderDialog.SelectedPath,
Path.GetFileName(sourcedirectory));
foreach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));
}
foreach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);
}
You can use a recursive function to do it:
private void button1_Click(object sender, EventArgs e)
{
this.CopyAll(new DirectoryInfo(#"D:\Original"), new DirectoryInfo(#"D:\Copy"));
}
private void CopyAll(DirectoryInfo oOriginal, DirectoryInfo oFinal)
{
foreach (DirectoryInfo oFolder in oOriginal.GetDirectories())
this.CopyAll(oFolder, oFinal.CreateSubdirectory(oFolder.Name));
foreach (FileInfo oFile in oOriginal.GetFiles())
oFile.CopyTo(oFinal.FullName + #"\" + oFile.Name, true);
}

Move all files in subfolders to another folder

My source path is C:\Music\ in which I have hundreds of folders called Album-1, Album-2 etc.
What I want to do is create a folder called Consolidated in my source path.
And then I want to move all the files inside my albums to the folder Consolidated, so that I get all the music files in one folder.
How can I do this?
Try like this
String directoryName = "C:\\Consolidated";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);
List<String> MyMusicFiles = Directory
.GetFiles("C:\\Music", "*.*", SearchOption.AllDirectories).ToList();
foreach (string file in MyMusicFiles)
{
FileInfo mFile = new FileInfo(file);
// to remove name collisions
if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
{
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
}
}
It will get all the files in the "C:\Music" folder (including files in the subfolder) and move them to the destination folder. The SearchOption.AllDirectories will recursively search all the subfolders.
Basically, that can be done with Directory.Move:
try
{
Directory.Move(source, destination);
}
catch { }
don't see any reason, why you shouldn't use this function. It's recursive and speed optimized
You can use the Directory object to do this, but you might run into problems if you have the same file name in multiple sub directories (e.g. album1\1.mp3, album2\1.mp3) so you might need a little extra logic to tack something unique onto the names (e.g. album1-1.mp4).
public void CopyDir( string sourceFolder, string destFolder )
{
if (!Directory.Exists( destFolder ))
Directory.CreateDirectory( destFolder );
// Get Files & Copy
string[] files = Directory.GetFiles( sourceFolder );
foreach (string file in files)
{
string name = Path.GetFileName( file );
// ADD Unique File Name Check to Below!!!!
string dest = Path.Combine( destFolder, name );
File.Copy( file, dest );
}
// Get dirs recursively and copy files
string[] folders = Directory.GetDirectories( sourceFolder );
foreach (string folder in folders)
{
string name = Path.GetFileName( folder );
string dest = Path.Combine( destFolder, name );
CopyDir( folder, dest );
}
}
public void MoveDirectory(string[] source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source[0], target));
while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile); File.Move(file, targetFile);
}
foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
Directory.Delete(source[0], true);
}
}
public class Folders {
public string Source {
get; private set;
}
public string Target {
get; private set;
}
public Folders(string source, string target) {
Source = source;
Target = target;
}
}
Something like this should get you rolling. You'll have to add error checking and what not (What if there is a subdirectory of source named "Consolidated"? What if Consolidated already exists? Etc.) This is from memory, so pardon any syntax errors, etc.
string source = #"C:\Music";
string[] directories = Directory.GetDirectories(source);
string consolidated = Path.Combine(source, "Consolidated")
Directory.CreateDirectory(consolidated);
foreach(var directory in directories) {
Directory.Move(directory, consolidated);
}
private static void MoveFiles(string sourceDir, string targetDir)
{
IEnumerable<FileInfo> files = Directory.GetFiles(sourceDir).Select(f => new FileInfo(f));
foreach (var file in files)
{
File.Move(file.FullName, Path.Combine(targetDir, file.Name));
}
}
You'll probably find this helpful to dedup your mp3's that have a different file name but same title.
source from David # msdn!
byte[] b = new byte[128];
string sTitle;
string sSinger;
string sAlbum;
string sYear;
string sComm;
FileStream fs = new FileStream(file, FileMode.Open);
fs.Seek(-128, SeekOrigin.End);
fs.Read(b, 0, 128);
bool isSet = false;
String sFlag = System.Text.Encoding.Default.GetString(b, 0, 3);
if (sFlag.CompareTo("TAG") == 0)
{
System.Console.WriteLine("Tag   is   setted! ");
isSet = true;
}
if (isSet)
{
//get   title   of   song;
sTitle = System.Text.Encoding.Default.GetString(b, 3, 30);
System.Console.WriteLine("Title: " + sTitle);
//get   singer;
sSinger = System.Text.Encoding.Default.GetString(b, 33, 30);
System.Console.WriteLine("Singer: " + sSinger);
//get   album;
sAlbum = System.Text.Encoding.Default.GetString(b, 63, 30);
System.Console.WriteLine("Album: " + sAlbum);
//get   Year   of   publish;
sYear = System.Text.Encoding.Default.GetString(b, 93, 4);
System.Console.WriteLine("Year: " + sYear);
//get   Comment;
sComm = System.Text.Encoding.Default.GetString(b, 97, 30);
System.Console.WriteLine("Comment: " + sComm);
}
System.Console.WriteLine("Any   key   to   exit! ");
System.Console.Read();
String directoryName = #"D:\NewAll\";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);
List<String> AllFiles= Directory
.GetFiles(#"D:\SourceDirectory\", "*.*", SearchOption.AllDirectories).ToList();
foreach (string file in AllFiles)
{
FileInfo mFile = new FileInfo(file);
// to remove name collisions
if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
{
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
}
else
{
string s = mFile.Name.Substring(0, mFile.Name.LastIndexOf('.'));
int a = 0;
while (new FileInfo(dirInfo + "\\" + s + a.ToString() + mFile.Extension).Exists)
{
a++;
}
mFile.MoveTo(dirInfo + "\\" + s + a.ToString() + mFile.Extension);
}
}
ToCopyIt is important to mention that you can't use the ".move()" method across volumes.
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.move?view=net-6.0
Move files:
string DirFrom = #"C:\MyWork";
string DirTo = #"E:\Archive";
DirectoryInfo DirInfoFrom = new DirectoryInfo(DirFrom);
DirectoryInfo DirInfoTo = new DirectoryInfo(DirTo);
if (!DirInfoTo.Exists)
{
Directory.CreateDirectory(DirTo);
}
foreach (FileInfo FileToCopy in DirInfoFrom.GetFiles())
{
FileToCopy.CopyTo(DirTo + FileToCopy.Name);
File.Delete(FileToCopy.FullName);
}
Tested 1/31/22 .NET4.8 VS2019
Copy all the folders (nested or not) including their files to another folder (destination) with one function call (static void CopyDirectory(string sourceDir, string destinationDir, bool recursive)):
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
We already had variant for copying directory structure, so this is just modified version of it for moving:
public static void MoveInner(string sourceDirName, string destDirName, bool moveSubDirs)
{
var dir = new DirectoryInfo(sourceDirName);
var dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it
if (!Directory.Exists(destDirName))
Directory.CreateDirectory(destDirName);
// Get the file contents of the directory to copy
var files = dir.GetFiles();
foreach (var file in files)
{
// Create the path to the new copy of the file
var temppath = Path.Combine(destDirName, file.Name);
// Move the file.
file.MoveTo(temppath);
}
// If copySubDirs is true, copy the subdirectories
if (!moveSubDirs)
return;
foreach (var subdir in dirs)
{
// Create the subdirectory
var temppath = Path.Combine(destDirName, subdir.Name);
// Move the subdirectories
MoveInner(subdir.FullName, temppath, moveSubDirs: true);
}
}
You loop through them and then simply run Move, the Directory class have functionality for listing contents too iirc.
MSDN : msdn.microsoft.com/en-us/library/bb762914.aspx
private void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
class Program
{
static void Main(string[] args)
{
movedirfiles(#"E:\f1", #"E:\f2");
}
static void movedirfiles(string sourdir,string destdir)
{
string[] dirlist = Directory.GetDirectories(sourdir);
moveallfiles(sourdir, destdir);
if (dirlist!=null && dirlist.Count()>0)
{
foreach(string dir in dirlist)
{
string dirName = destdir+"\\"+ new DirectoryInfo(dir).Name;
Directory.CreateDirectory(dirName);
moveallfiles(dir,dirName);
}
}
}
static void moveallfiles(string sourdir,string destdir)
{
string[] filelist = Directory.GetFiles(sourdir);
if (filelist != null && filelist.Count() > 0)
{
foreach (string file in filelist)
{
File.Copy(file, string.Concat(destdir, "\\"+Path.GetFileName(file)));
}
}
}
}

Categories

Resources