View Full Version : VB.Net, how to copy folder contents

02-14-2005, 11:24 PM
Hello, I am having a .Net problem, not sure this is posible or not, please help.

How do I copy a folder and all the sub folder and files within the folder.

example, I want to copy C:/hello, in folder hello, there is folder hi, in folder hi, there is a file called mike.txt

how do I copy everything in C:/hello?

Thank you

Dr. Evil
02-15-2005, 08:42 AM
I don't know all the calls and such in VB, but basically you want to start with a FindFirstFile(), FindNextFile() loop (or whatever the finding functions are in VB) and when you come accross a folder, recurse into that folder and/or create one in the destination folder. If what you hit was a file, copy it to the needed destination. It's kind of hard to explain, and this code sample's in C, but maybe you can get the picture of what you could do from here:

#include <windows.h>
#include <stdio.h>

int FindFilesWithinDirectory(LPSTR start_dir)
WIN32_FIND_DATA find_data;
HANDLE find_h;
DWORD find_ret;
int ret;
char *file_name, begin_again[MAX_PATH];

ret = 0;
find_h = FindFirstFile(start_dir, &find_data);
if(find_h != NULL)
printf("Files within %s\n", start_dir);
if((file_name = strrchr(find_data.cFileName, '\\')) != NULL) file_name++;
else file_name = find_data.cFileName;

if((find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
(strcmp(file_name, "..")) /*make sure we don't back track*/ &&
(strcmp(file_name, "."))) /*no point in going into our own directory*/
strcpy(begin_again, start_dir);
begin_again[(strlen(begin_again)-3)] = 0; //get rid of previous *.*
strcat(begin_again, find_data.cFileName);
strcat(begin_again, "\\*.*");

ret = FindFilesWithinDirectory(begin_again);
else puts(file_name);

if(ret) break;
if(!FindNextFile(find_h, &find_data)) find_ret = GetLastError();
else find_ret = 0;
while(find_ret != ERROR_NO_MORE_FILES);
else ret = 1;

return ret;

int main(int argc, char *argv[])
char begin[10], *error = 0;

strcpy(begin, getenv("SystemDrive"));
strcat(begin, "\\*.*");

case 0 : break;
case 1 : error = "Invalid directory or no specified files within such a directory"; break;
default : error = "Unknown error"; break;
if(error) puts(error);

return 0;

That just simply lists all the files within the system drive, but very little modification is needed to make it copy all the files and folders.

02-15-2005, 04:38 PM
To go with the Dr's example, heres a good Recursive example in .NET

Recursive (http://www.visualbasicforum.com/showthread.php?t=158264)