abhi
abhi

Reputation: 23

Folder structure copy in C#

I am creating an application where we can select a destination machine over the network and it would copy a selected source file on a specific folder. Essentially, it's intended to work on application servers where a single machine would have multiple app servers, apache tomcat in this case.

Currently, my code is able to process one source file to a specific destination. It does it for all the tomcat folder's present on that machine(tomcat1, tomcat2.. etc..)

I am using directoryinfo to select the list of folders.

DirectoryInfo diTom = new DirectoryInfo(txtTomcat.Text);

where txtTomcat.text is the network path of the tomcat folder. Then I am using a foreach loop

foreach (DirectoryInfo subDir in diTomDirs)

Thus, for each entry of tomcat in the directory info, it executes a simple File.Copy code, copying the file inside the folder specified for each tomcat.

Now, I want to extend my applications functionality to consider source folders, instead of just file.

e.g. I have folder A, containing file1.txt and folder B. Folder B in turn contains file2.txt and file3.txt. Similar structure would also exit on the destination tomcat, but with few other folders and files.

I'd like to give the source folder A as the source, and it should execute the existing code of file copy but now, copying files from source folder to the corresponding folder on the destination, i.e. A(source) -> A(server) and files from B(source) to B(server).

I hope I didn't make it sound too confusing.. :(

I guess it would be the foreach logic which I need to tweak but not able to figure out how.

Any clues?

Many Thanks,

Abhi

Upvotes: 1

Views: 3706

Answers (2)

bryanmac
bryanmac

Reputation: 39296

One option is to use robocopy. It is much more robust (retries) and optimal (parallel) than something you will likely have time to invest in. As slugseter noted it shipped on 2008.

I've known many large companies that use it to push out their front end server bits ...

You can get it from the windows resource kit tools:

http://www.microsoft.com/download/en/details.aspx?id=17657

Upvotes: 0

Salvatore Previti
Salvatore Previti

Reputation: 9050

The simpler way is to use a recursive function.

public static void ProcessDirectory(string targetDirectory) 
{
    foreach(string fileName in Directory.GetFiles(targetDirectory))
        ProcessFile(fileName);

    foreach(string subdirectory in Directory.GetDirectories(targetDirectory))
        ProcessDirectory(subdirectory);

    // Here is called for each directory and sub directory
}

public static void ProcessFile(string path) 
{
    // Here is called for each file in all subdirectories
}

Upvotes: 2

Related Questions