HOW TO >VB.NET
Copiare un intera Directory e relative sottocartelle. Inserire sul form una Label (LbProgressivo) Metodo 1 : copia con stato di avanzamento
Copiare un intera Directory e relative sottocartelle. Inserire sul form una Label (LbProgressivo) Metodo 1 : copia con stato di avanzamento
- Imports System
- Imports System.IO
- Public Class Form1
- Public ProgFiles, TotFiles As Integer
- Private Sub Bt1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bt1.Click
- Dim DirectoryOrigine As String = "c:\test"
- Dim DirectoryDestinazione As String = "c:\testnew"
- Try
- 'Conto i files nella directory origine per visualizzare lo stato di avanzamento
- Dim dDir1 As New DirectoryInfo(DirectoryOrigine)
- TotFiles = dDir1.GetFiles("*.*", SearchOption.AllDirectories).Length
- ProgFiles = 0
- 'Effettuo la copia della directory
- CopyDirectory(DirectoryOrigine, DirectoryDestinazione, LbProgressivo)
- MessageBox.Show("Operazione completata")
- 'Ripristino lo stato precedente
- '(la riga seguente e' da togliere nell'utilizzo della routine)
- Directory.Delete(DirectoryDestinazione, True)
- Catch ex As Exception
- MessageBox.Show(ex.Message & Environment.NewLine & ex.StackTrace)
- End Try
- End Sub
- Sub CopyDirectory(ByVal Origine As String, ByVal Destinazione As String, ByVal Lb As Label)
- Dim Lb1 As Label = Lb
- Dim CartellaCorrente As DirectoryInfo = New DirectoryInfo(Origine)
- Dim Archivo As FileInfo
- Dim Cartella As DirectoryInfo
- For Each Archivo In CartellaCorrente.GetFiles()
- If Not Directory.Exists(Destinazione) Then Directory.CreateDirectory(Destinazione)
- Try
- Archivo.CopyTo(Path.Combine(Destinazione, Archivo.Name))
- ProgFiles += 1
- Lb1.Text = "In fase di copia " & ProgFiles & " file di "
- Lb1.Text += TotFiles & " ( " & Archivo.Name & ")"
- Application.DoEvents()
- Catch ex As Exception
- 'Errore in copia file...
- MessageBox.Show(ex.Message & Environment.NewLine & ex.StackTrace)
- End Try
- Application.DoEvents()
- Next
- For Each Cartella In CartellaCorrente.GetDirectories()
- Dim subDirectory As String = Path.Combine(Destinazione, Cartella.Name)
- Try
- Directory.CreateDirectory(subDirectory)
- Catch ex As Exception
- 'Errore in creazione directory...
- MessageBox.Show(ex.Message & Environment.NewLine & ex.StackTrace)
- End Try
- CopyDirectory(Cartella.FullName, subDirectory, Lb1)
- Next
- End Sub
- End Class
