Solved

Copy all folders, subfolders and files

Posted on 2012-03-13
11
289 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 74

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
 
LVL 74

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 74

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 74

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 74

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 74

Expert Comment

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

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

759 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now