Results 1 to 2 of 2

Thread: How to copying the file from one Directory to another directory by create the folder

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    6

    How to copying the file from one Directory to another directory by create the folder

    Hi,
    I have some problem with copying the file from one Directory to another directory by create the folder if that folder is not exists in destination directory.
    Example:
    Source path: C:\temp\test\1.txt
    destination path: C:\Data\
    if C:\Data\ doesn't contains "temp" or "test" folder, it should create the folder before copy the 1.txt.

    Copied to C:\Data\temp\test\1.txt

    Below is my code. But it doesn't work..Please help

    Code:
      Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click
                  Dim sourcepath As String = "C:\temp\test\1.txt"
            Dim DestPath As String = "C:\Data\"
            CopyDirectory(sourcepath, DestPath)
        
        End Sub
    
    
    
        Private Shared Sub CopyDirectory(sourcePath As String, destPath As String)
        	If Not Directory.Exists(destPath) Then
        		Directory.CreateDirectory(destPath)
        	End If
        
        	For Each file__1 As String In Directory.GetFiles(sourcePath)
        		Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
        		File.Copy(file__1, dest)
        	Next
        
        	For Each folder As String In Directory.GetDirectories(sourcePath)
        		Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
        		CopyDirectory(folder, dest)
        	Next
        End Sub

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: How to copying the file from one Directory to another directory by create the fo

    You are passing in a file path to the 'sourcePath' parameter and then do this:
    Code:
    For Each file__1 As String In Directory.GetFiles(sourcePath)
    and this:
    Code:
    For Each folder As String In Directory.GetDirectories(sourcePath)
    If sourcePath is a file then how is it going to have files and directories in it?

    If you want to copy the contents of a folder from location to another then maybe you should use My.Computer.FileSystem.CopyDirectory.

Tags for this Thread

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