title: How to copy a file from one directory to another directory by creating the folder if that folder does not exist
body: <p>I have some problem with copying the file from one directory to another directory by creating the folder if that folder does not exist in the destination directory.</p>
  
  <p>Example:</p>
  
  <ul>
  <li>Source path: <code>C:\temp\test\1.txt</code></li>
  <li>Destination path: <code>C:\Data\</code></li>
  </ul>
  
  <p>If <code>C:\Data\</code> doesn't contain "temp" or "test" folder, it should create the folder before coping <code>1.txt</code>.</p>
  
  <p>Copied to <code>C:\Data\temp\test\1.txt</code></p>
  
  <p>Below is my code. But it doesn't work..</p>
  
  <pre><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
  </code></pre>