小新二三事 二三事 電視精/戲院 ASP .NET 新手工作日誌

2009年8月11日星期二

ASP.NET Code: copy file and folder recursively

ASP.NET Code: copy file and folder recursively

Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String, ByVal overwrite As Boolean)
Dim sourceDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(sourcePath)
Dim destDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(destPath)
'the source directory must exist for our code to run
If (sourceDir.Exists) Then
'if the destination folder does not exist, create it
If Not (destDir.Exists) Then
destDir.Create()
End If
'loop through all the files of the current directory
'and copy them if overwrite=true or they do not exist
Dim file As System.IO.FileInfo
For Each file In sourceDir.GetFiles()
If (overwrite) Then
file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), True)
Else
If ((System.IO.File.Exists(System.IO.Path.Combine(destDir.FullName, file.Name))) = False) Then
file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), False)
End If
End If
Next
'loop through all the subfolders and call this method recursively
Dim dir As System.IO.DirectoryInfo
For Each dir In sourceDir.GetDirectories()
If (dir.FullName <> Server.MapPath(strDestinationDir)) Then
CopyDirectory(dir.FullName, System.IO.Path.Combine(destDir.FullName, dir.Name), overwrite)
End If
Next
lblStatusMessage.Text = "Folder copied successfully"
lblStatusMessage.Visible = True
'if source directory does not exist
Else
lblStatusMessage.Text = "Error: source folder does not exist!"
lblStatusMessage.Visible = True
End If
End Sub

code from
http://www.xefteri.com/articles/show.cfm?id=16

good example

沒有留言: