Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Copy all folders, subfolders and files

Posted on 2012-03-13
11
Medium Priority
?
298 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
11 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 300 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 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

715 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