Solved

Copy all folders, subfolders and files

Posted on 2012-03-13
11
292 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VS.net 2010 11 48
write xml in vb.net 2 33
Database Connections Not being returned to Connection Pool 7 34
VS 2015 is giving [No relevant source lines] 2 29
This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
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…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

829 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