Results 1 to 14 of 14

Thread: How to copy sub-folders?

  1. #1

    Thread Starter
    Frenzied Member MrGTI's Avatar
    Join Date
    Oct 2000
    Location
    Ontario, Canada
    Posts
    1,277

    Question How to copy sub-folders?

    Using the search i've had no problems figuring out how to copy the contents of a folder from one place to another.

    But what about copying sub-folders? I'd like to also copy all the sub-folders. Take a look at this:
    VB Code:
    1. 'Using this import: Imports System.IO
    2.  
    3. 'Locate where the program is
    4. Dim sAppPath As String = System.Environment.CurrentDirectory
    5. 'Use the test directory with sample files in it
    6. Dim xSourceFolder As New DirectoryInfo(sAppPath & "\test")
    7. Dim xDestinationFolder As New DirectoryInfo(sAppPath & "\test2")
    8.  
    9. 'Removes previous instance of the folder and any sub-directories, then creates it fresh
    10. If xDestinationFolder.Exists = True Then xDestinationFolder.Delete(True)
    11. xDestinationFolder.Create()
    12.  
    13. 'Copies each file from the source foldr into the destination folder
    14. Dim xFile As FileInfo
    15. For Each xFile In xSourceFolder.GetFiles
    16.      xFile.CopyTo(xDestinationFolder.FullName & "\" & xFile.Name)
    17. Next xFile
    18. Beep()
    What if there are a few sub-folders in the "test" folder? How can i copy them and all their contents? I know i'll need a recursive loop, but how do i identify the folder?
    ~Peter


  2. #2
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    according to this link , there is no recursive directory copy .
    http://www.dotnet247.com/247referenc.../16/83818.aspx
    Did you try something like this :

    VB Code:
    1. Dim folds As IO.DirectoryInfo
    2. folds.GetDirectories()

  3. #3

    Thread Starter
    Frenzied Member MrGTI's Avatar
    Join Date
    Oct 2000
    Location
    Ontario, Canada
    Posts
    1,277

    Thumbs up

    Between those two items, i think i now have enough to build it myself. Thanks Pirate.

    I'll let you know what i get when it's all done.
    ~Peter


  4. #4

    Thread Starter
    Frenzied Member MrGTI's Avatar
    Join Date
    Oct 2000
    Location
    Ontario, Canada
    Posts
    1,277

    Talking

    Works like a charm. Thanks again.
    ~Peter


  5. #5
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    Glad to hear it is working !

  6. #6
    PowerPoster
    Join Date
    Jan 2001
    Location
    Florida
    Posts
    3,216
    Originally posted by Pirate
    according to this link , there is no recursive directory copy .
    http://www.dotnet247.com/247referenc.../16/83818.aspx
    Did you try something like this :

    VB Code:
    1. Dim folds As IO.DirectoryInfo
    2. folds.GetDirectories()
    If you were in C# you could simply do -

    Code:
    using System.IO;
    
    Directory.Move();

  7. #7

    Thread Starter
    Frenzied Member MrGTI's Avatar
    Join Date
    Oct 2000
    Location
    Ontario, Canada
    Posts
    1,277
    A possible solution. But i'm a VB.NET guy myself. And i don't want to move the folder; just make a copy of it.
    ~Peter


  8. #8
    PowerPoster
    Join Date
    Jan 2001
    Location
    Florida
    Posts
    3,216
    Originally posted by MrGTI
    A possible solution. But i'm a VB.NET guy myself. And i don't want to move the folder; just make a copy of it.
    Sorry, still learning .NET like us all. It appears, whether VB or C#, to COPY a directory we will all have to work a little harder.

  9. #9
    Member
    Join Date
    Mar 2003
    Posts
    34
    Here is a small utility class I just wrote that will copy a directory and its contents. The last parameter of the Copy() method specifys if a shallow copy (excluding subdirectories) or deep copy is performed.

    Code:
    using System;
    using System.IO;
    
    public class Folder {
    
        public static void Copy(string target, string destination, bool deep) {
    	// verify the source directory exists. also, make sure the destination directory 
    	// does not already exist. if any of the conditions fail, throw io exception		
    	if(Directory.Exists(target)) {
    	    if(!Directory.Exists(destination)){
    	        Directory.CreateDirectory(destination);
    		ProcessDirectory(target, destination, deep);
    	    }else {
    		throw new IOException("Destination directory already exists");
    	    }
    	}else {
    	    throw new DirectoryNotFoundException("Directory does not exist");
    	}
        }
    
        private static void ProcessDirectory(string target, string destination, bool deep) {
    	// remove trailing backslashes from directory path variables
    	target = (target.EndsWith(@"\") ? target.Substring(0, target.Length - 1) : target);
    	destination = (destination.EndsWith(@"\") ? destination.Substring(0, destination.Length - 1) : destination);
    	// create the new destination directory
    	DirectoryInfo current = new DirectoryInfo(target);
    	string directoryPath = String.Concat(destination, @"\", current.Name);		
    	Directory.CreateDirectory(directoryPath);
    	// copy all files within the directory to the new directory
    	string[] fileEntries = Directory.GetFiles(target);
    	foreach(string fileName in fileEntries) {
    	    CopyFile(fileName, directoryPath);
    	}
    	if(deep) { 
    	    // recursively call method for each subdirectory
    	    string [] subdirectoryEntries = Directory.GetDirectories(target);
    	    foreach(string subdirectory in subdirectoryEntries) {
    		ProcessDirectory(subdirectory, directoryPath, true);
       	    }
    	}
         }
    
        private static void CopyFile(string source, string destination) {
    	// if the source file exists, copy to the new destination
    	if(File.Exists(source)) {
    	    FileInfo sourceFile = new FileInfo(source);
    	    sourceFile.CopyTo(String.Concat(destination, @"\", sourceFile.Name));
    	}
        }
    
        static void Main() {
    	Folder.Copy(@"c:\sonysys", @"d:\copy\", true);	
        }
    }
    Last edited by SimonVega; Mar 12th, 2003 at 01:59 AM.

  10. #10
    Member
    Join Date
    Dec 2002
    Location
    NY, USA
    Posts
    52
    Code:
    RecursiveDirectoryCopy(ByVal sourceDir As String, ByVal destDir As String, ByVal fRecursive As Boolean, ByVal overWrite As Boolean)
    
    
    Code:' Usage: 
    ' Copy Recursive with Overwrite if exists. 
    ' RecursiveDirectoryCopy("C:\Data", "D:\Data", True, True) 
    ' Copy Recursive without Overwriting. 
    ' RecursiveDirectoryCopy("C:\Data", "D:\Data", True, False) 
    ' Copy this directory Only. Overwrite if exists. 
    ' RecursiveDirectoryCopy("C:\Data", "D:\Data", False, True) 
    ' Copy this directory only without overwriting. 
    ' RecursiveDirectoryCopy("C:\Data", "D:\Data", False, False) 
    
    ' Recursively copy all files and subdirectories from the specified source to the specified 
    ' destination. 
    Private Sub RecursiveDirectoryCopy(ByVal sourceDir As String, ByVal destDir As String, ByVal fRecursive As Boolean, ByVal overWrite As Boolean) 
        Dim sDir As String 
        Dim dDirInfo As IO.DirectoryInfo 
        Dim sDirInfo As IO.DirectoryInfo 
        Dim sFile As String 
        Dim sFileInfo As IO.FileInfo 
        Dim dFileInfo As IO.FileInfo 
        ' Add trailing separators to the supplied paths if they don't exist. 
        If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then 
            sourceDir &= System.IO.Path.DirectorySeparatorChar 
        End If 
        If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then 
            destDir &= System.IO.Path.DirectorySeparatorChar 
        End If 
        'If destination directory does not exist, create it. 
        dDirInfo = New System.IO.DirectoryInfo(destDir) 
        If dDirInfo.Exists = False Then dDirInfo.Create() 
        dDirInfo = Nothing 
        ' Recursive switch to continue drilling down into directory structure. 
        If fRecursive Then 
            ' Get a list of directories from the current parent. 
            For Each sDir In System.IO.Directory.GetDirectories(sourceDir) 
                sDirInfo = New System.IO.DirectoryInfo(sDir) 
                dDirInfo = New System.IO.DirectoryInfo(destDir & sDirInfo.Name) 
                ' Create the directory if it does not exist. 
                If dDirInfo.Exists = False Then dDirInfo.Create() 
                ' Since we are in recursive mode, copy the children also 
                RecursiveDirectoryCopy(sDirInfo.FullName, dDirInfo.FullName, fRecursive, overWrite) 
                sDirInfo = Nothing 
                dDirInfo = Nothing 
            Next 
        End If 
        ' Get the files from the current parent. 
        For Each sFile In System.IO.Directory.GetFiles(sourceDir) 
            sFileInfo = New System.IO.FileInfo(sFile) 
            dFileInfo = New System.IO.FileInfo(Replace(sFile, sourceDir, destDir)) 
            'If File does not exist. Copy. 
            If dFileInfo.Exists = False Then 
                sFileInfo.CopyTo(dFileInfo.FullName, overWrite) 
            Else 
                'If file exists and is the same length (size). Skip. 
                'If file exists and is of different Length (size) and overwrite = True. Copy 
                If sFileInfo.Length <> dFileInfo.Length AndAlso overWrite Then 
                    sFileInfo.CopyTo(dFileInfo.FullName, overWrite) 
                'If file exists and is of different Length (size) and overwrite = False. Skip 
                ElseIf sFileInfo.Length <> dFileInfo.Length AndAlso Not overWrite Then 
                    Debug.WriteLine(sFileInfo.FullName & " Not copied.") 
                End If 
            End If 
            sFileInfo = Nothing 
            dFileInfo = Nothing 
        Next 
    End Sub
    Iouri Boutchkine

  11. #11
    New Member
    Join Date
    Aug 2003
    Posts
    2

    Might be a dumb idea

    Hi together!

    Might be a dumb idea, but why not use the dos command?

    Write it into a batch and shell() it?

    ok, you might have problems getting back a feedback, but for me it worked fine. rude, not professional, but worked!

    Anything i missed? Being a Real VB beginner!!!!!

    Example:

    ' create a string, that is using the dos command move "source" "Target" with " for enabling blanks in pathnames
    retvalue = "move " + Chr(34) + source + Chr(34) + " " + Chr(34) + target2 + Chr(34)

    ' create a bachfile, write the doscommand in there
    Open "batchfile.bat" For Output As #2 'save file
    Write #2, retvalue
    Close #2

    ' execute the batchfile
    obj = Shell("batchfile.bat", vbHide)

    ' and delete it
    Kill "batchfile.bat"

  12. #12
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256

    Re: Might be a dumb idea

    Originally posted by denkr
    Hi together!

    Might be a dumb idea, but why not use the dos command?

    Write it into a batch and shell() it?

    ok, you might have problems getting back a feedback, but for me it worked fine. rude, not professional, but worked!

    Anything i missed? Being a Real VB beginner!!!!!

    Example:

    ' create a string, that is using the dos command move "source" "Target" with " for enabling blanks in pathnames
    retvalue = "move " + Chr(34) + source + Chr(34) + " " + Chr(34) + target2 + Chr(34)

    ' create a bachfile, write the doscommand in there
    Open "batchfile.bat" For Output As #2 'save file
    Write #2, retvalue
    Close #2

    ' execute the batchfile
    obj = Shell("batchfile.bat", vbHide)

    ' and delete it
    Kill "batchfile.bat"
    Yes you miss quite a lot. You might be in the wrong forum. BTW, you might wanna start learning VB.NET since you are a beginner.

  13. #13
    New Member
    Join Date
    Aug 2003
    Posts
    2
    except that the coding not being vb.net,

    does the method not work? write a textfile with a doscommand and execute it with a shell?

    Not possible in VB.NET?

    Mainly was not to have the ideal sollution for VB.NET, was to show the way, I used!


  14. #14
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    Originally posted by denkr
    except that the coding not being vb.net,

    does the method not work? write a textfile with a doscommand and execute it with a shell?

    Not possible in VB.NET?

    Mainly was not to have the ideal sollution for VB.NET, was to show the way, I used!

    Writing DOS Command in a patch-like file is not the ideal solution , although it can be run in .NET app .

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width