copy folder content to other location

weronpc

Member
Joined
Feb 14, 2005
Messages
6
Programming Experience
1-3
Hello, I am having a .Net problem, not sure this is posible or not, please help.

How do I copy a folder and all its content within the folder to another location?

example, I want to copy C:/hello, in folder hello there is folder hi, in folder hi there is a file called mike.txt

how do I copy everything in C:/hello?

Thank you
 
hmm, i know there's system.io.file.copy but that's for 1 file at a time and doesnt do folders (to my knowledge)
 
True, there is no function already existing to copy the folder and contents.
But you can write one.
VB.NET:
Public Function CopyDirectory(ByVal Src As String, ByVal Dest As String, Optional _
  ByVal bQuiet As Boolean = False) As Boolean
    If Not Directory.Exists(Src) Then
        Throw New DirectoryNotFoundException("The directory " & Src & " does not exists")
    End If
    If Directory.Exists(Dest) AndAlso Not bQuiet Then
          If MessageBox.Show("directory " & Dest & " already exists." & vbCrLf & _
          "If you continue, any files with the same name will be overwritten", _
          "Continue?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, _
          MessageBoxDefaultButton.Button2) = DialogResult.Cancel Then Exit Function
    End If
 
    'add Directory Seperator Character (\) for the string concatenation shown later
    If Dest.Substring(Dest.Length - 1, 1) <> Path.DirectorySeparatorChar Then
        Dest += Path.DirectorySeparatorChar
    End If
    If Not Directory.Exists(Dest) Then Directory.CreateDirectory(Dest)
    Dim Files As String()
    Files = Directory.GetFileSystemEntries(Src)
    Dim element As String
    For Each element In Files
        If Directory.Exists(element) Then
            'if the current FileSystemEntry is a directory,
            'call this function recursively
            CopyDirectory(element, Dest & Path.GetFileName(element), True)
        Else
            'the current FileSystemEntry is a file so just copy it
            File.Copy(element, Dest & Path.GetFileName(element), True)
        End If
    Next
    Return True
End Function
 
'Example usage:
Private Sub cmdCopyDir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles cmdCopyDir.Click
    If CopyDirectory("D:\somePath", "C:\someOtherPath") Then
        MessageBox.Show("Success copying directory")
    Else
        MessageBox.Show("Error copying directory")
    End If
End Sub
This function takes two absolute paths (source directory and destination directory) as parameters and returns a Boolean equal to True when the copy succeeds. The optional parameter (bQuiet), if set to False, will cause a prompt to be displayed to warn the user that any destination files with the same name will be overwritten if the Destination directory exists. As written, the prompt is only shown for the initial directory and not all subDirectories.
 
i want to thank you

thanx a million for the code. it helped alot.
i have a simple question:
how do i run a webapplication on the local host, with the "shell" command?
for example:
shell("c:\inetpub\wwwroot\odshir\......")
i also want the start up page to be shown first as i programmed in the application.
thanx
odelya
 
Just a quick note Paszt: you don't need to use the bit that checks for a slash and adds one if it's not there. The IO.Path.Combine method does just that.

IO.Path.Combine("C:\Hello\", "Goodbye.txt") and
IO.Path.Combine("C:\Hello", "Goodbye.txt")

both return "C:\Hello\Goodbye.txt".
 
jmcilhinney Wow thats realy reduce the above code, i think it is much better to use the functions that VB.Net itself offers to u instaed of adding new userdefined one.

great
 
readraj said:
jmcilhinney Wow thats realy reduce the above code, i think it is much better to use the functions that VB.Net itself offers to u instaed of adding new userdefined one.

great
I hope you haven't misunderstood me. You still need to write your own function as Paszt has. My suggestion merely reduces the code provided by a couple of lines.
 
jmcilhinney No No Not at all,
I am not saying that u should not write any user defined functions, U have too but whereever possible u should use the simple ways that .NET offers...
 
Thanks for the tip Jim. That's one function of the Path class that I had missed 'till now. Using it, you could remove 4 lines (including the comment).
Always learning :).
 
Some Quick Questions...

Hello,

I was wondering how I might set a Progressbar's Value or Step to go along with the copy of the file.

Is it possible to set an "Exit Function" on the click of the FolderBrowserDialog's Cancel Button?

I noticed that if you hit the Cancel button it still takes you to the "Overwrite" messagebox.

Well thanks for your time and the great function as I find it very useful! :)

Cheers!

Waxxxz
 
If you want to provide a progress for this operation you would need to calculate the total size of all the files to be copied first and then advance the ProgressBar propertionally to the size of each file as each gets copied. If you want the progress to be any more accurate than that then you're in for a lot of hassle.

FileBrowserDialog.ShowDialog returns a DialogResult value. The only values it can return are OK and Cancel, so you just need to test for one or the other. You would usually test for OK and only proceed if it's found.
 
I gave this code a try and think I'm missing some references as I'm getting a lot of not declared values? I'm new to this .Net stuff so wondering how to identify from a string of code what references it needs? So this code for example how would a newbie identify the reference needed.

Thanks for the help!!

Mark
 
Mark, in your case use .Net 2.0s My.Computer.FileSystem.CopyDirectory method.
 
Back
Top