Solved

Copy all folders, subfolders and files

Posted on 2012-03-13
11
291 Views
Last Modified: 2012-03-14
I am trying to develop a program that allows me to provide a source and destination path, then copy the same structure from the source to the destination directory but it is failing. It only copies the files into the main folder not replicating the whole structure nor copying the files also :(

This is the code I am using:

Private Sub btnNormalizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNormalizar.Click
        Dim sourceDir As String = txtOrigen.Text
        Dim backupDir As String = txtDestino.Text

        Try
            Dim docList As String() = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories)

            ' Copy doc files.
            For Each f As String In docList
                'Remove path from the file name.
                Dim fName As String = f.Substring(sourceDir.Length + 1)

                ' Use the Path.Combine method to safely append the file name to the path.
                ' Will overwrite if the destination file already exists.
                File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
            Next

            For Each f As String In docList
                File.Delete(f)
            Next

        Catch dirNotFound As DirectoryNotFoundException
            Console.WriteLine(dirNotFound.Message)
        End Try

        MsgBox("Done!")
    End Sub

Open in new window

0
Comment
Question by:José Perez
  • 6
  • 4
11 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 100 total points
ID: 37717325
I think a small modification would get you going:

...

For Each f As String In docList
    'Remove path from the file name.
    Dim fName As String = f.Substring(sourceDir.Length + 1)
    Dim dName As String

    ' Combine existing filename/subfolder with new directory name to get destination file path
    fName = Path.Combine(backupDir, fName)
    
    ' Get just the directory component of the new path
    dName = Path.GetDirectoryName(fName)

    ' If that directory described within "dName" doesn't exist, create it
    If Not Directory.Exists(dName) Then
        Directory.CreateDirectory(dName)
    End If

    ' Use the Path.Combine method to safely append the file name to the path.
    ' Will overwrite if the destination file already exists.
    File.Copy(f, fName, True)
Next

...

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37717691
0
 
LVL 2

Author Comment

by:José Perez
ID: 37719552
kaufmed, it works but it does not create the folders which are empty, I need to create them also.
0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37719610
Ah. Then you would probably want a recursive function to copy everything. However, did you look into CodeCruiser's CopyDirectory suggestion? I wasn't aware of it before he posted, and I think it would save you quite a bit of code. It should do exactly what you are seeking to do--in one line!
0
 
LVL 2

Author Comment

by:José Perez
ID: 37720608
CopyDirectory does not work for me because I need to identify every file so I can rename it.

What I'll do is to use kaufmed code and I will forget about the empty folders, at least, by now.

Thanks a lot.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37720718
It's not terribly involved to create the recursive function to do this; I just didn't realize you wanted a bit more functionality that what is provided by the aforementioned method.

A recursive function to create the folder hierarchy could be:

Sub CreateFolderHierarchy(ByVal sourcePath As String, ByVal destinationPath As String)
    For Each subfolder As String In Directory.GetDirectories(sourcePath)
        Dim existingFolderName As String = Path.GetFileName(subfolder)
        Dim newFolderPath As String = Path.Combine(destinationPath, existingFolderName)

        If Not Directory.Exists(newFolderPath) Then
            Directory.CreateDirectory(newFolderPath)
        End If

        CreateFolderHierarchy(subfolder, newFolderPath)
    Next
End Sub

Open in new window


...then it would simply be a matter of passing the source and destination directories:

...

Try
    Dim docList As String() = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories)

    CreateFolderHierarchy(sourceDir, backupDir)  ' HERE
    
    ' Copy doc files.
    For Each f As String In docList
    
...

Open in new window


This should create all directories in the destination--even the empty ones.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37720733
P.S.

The above example of calling this new function uses the code from your original post, not the code from my first post.
0
 
LVL 2

Author Closing Comment

by:José Perez
ID: 37721452
kaufmed provided me the solution to create de folders with the files. I think it works for what I am looking for. The empty folders creation can be taken as less important for the solution.

thanks a lot.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37721733
The empty folders creation can be taken as less important for the solution.
Did you see my last post? That function would create the folders regardless of their contents.
0
 
LVL 2

Author Comment

by:José Perez
ID: 37721777
Yes. Thanks :)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37721793
OK   = )
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question