Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Tomas1982 en 10 Febrero 2017, 18:40 pm



Título: Ayuda con Copiador de USB
Publicado por: Tomas1982 en 10 Febrero 2017, 18:40 pm
Buenas ante todos: Estoy tratando de resolver un problema que no tengo idea de como hacerlo. (En cuestión)  Quiero copiar las USB que son introducida en mi PC. Tengo el código que hace esa función pero si se esta copiando al momento de insertar otro USB esa ya no me la copia, Como puedo resolver ese problema.   

Código
  1.  
  2. ‘Estructura de datos que almacena la gestión de conexiones
  3. Public Structure dispositivo
  4.  Public dispTamaño As Integer
  5.  Public dispTipo As Integer
  6.  Public dispReserv As Integer
  7.  Public dispMask As Integer
  8. End Structure
  9.  
  10. Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
  11.  
  12.  ‘Se ha producido un cambio en los dispositivos
  13.  Const deviceChange As Integer = &H219
  14.  ‘El sistema detecta un nuevo dispositivo
  15.  Const deviceArrival As Integer = &H8000
  16.  ‘Solicita retirada del dispositivo
  17.  Const deviceQueryRemove As Integer = &H8001
  18.  ‘Ha fallado la retirada del dispositivo
  19.  Const devideQueryRemoveFailed As Integer = &H8002
  20.  ‘Pendiente extracción del dispositivo
  21.  Const deviceRemovePending As Integer = &H8003
  22.  ‘Dispositivo extraído del sistema
  23.  Const deviceRemoveComplete As Integer = &H8004
  24.  ‘ Volumen lógico (Se ha insertado un disco)
  25.  Const deviceTypeVolume As Integer = &H2
  26.  
  27.  Select Case m.Msg
  28.    ‘Cambian los dispositivos del sistema
  29.    Case deviceChange
  30.    Select Case m.WParam.ToInt32
  31.      ‘Llegada de un dispositivo
  32.      Case deviceArrival
  33.      Dim devType As Integer = Marshal.ReadInt32(m.LParam, 4)
  34.      ‘Si es un volumen lógico..(unidad de disco)
  35.      If devType = deviceTypeVolume Then
  36.        Dim vol As dispositivo
  37.        vol = CType(Marshal.PtrToStructure(m.LParam, GetType(dispositivo)), dispositivo)
  38.        MessageBox.Show(”Se insertó un dispositivo en la unidad ” & LetraUnidad(vol.dispMask) & “.”)
  39. 'La mando a copiar
  40. copiar()
  41.        ‘ACA HAGO EL TRATAMIENTO DEL DISPOSITIVO INSERTADO
  42.      End If
  43.    Case deviceRemoveComplete
  44.      MessageBox.Show(”Se retiró el dispositivo.”)
  45.    End Select
  46.  End Select
  47.  
  48.  ‘Ahora se usa el manejador predeterminado
  49.  MyBase.WndProc(m)
  50. End Sub
  51.  
  52. Private Function LetraUnidad(ByVal unitmask As Integer) As Char
  53.  Dim units() As Char = {”A”, “B”, “C”, “D”, “E”, “F”, “G”,
  54.      “H”, “I”, “J”, “K”, “L”, “M”, “N”, “O”, “P”,
  55.      “Q”, “R”, “S”, “T”, “U”, “V”, “W”, “X”, “Y”, “Z”}
  56.  Dim i As Integer = 0
  57.  ‘Convetimos la máscara en un array primario y buscamos
  58.  ‘el índice de la primera ocurrencia (la letra de unidad)
  59.  Dim ba As System.Collections.BitArray
  60.  ba = New System.Collections.BitArray(System.BitConverter.GetBytes(unitmask))
  61.  
  62.  For i = 0 To ba.Length
  63.    If ba(i) = True Then
  64.    Exit For
  65.  End If
  66.  Next
  67.  
  68.  Return units(i)
  69. End Function
  70.  
  71.  
  72.  


Título: Re: Ayuda con Copiador de USB
Publicado por: Serapis en 10 Febrero 2017, 19:09 pm
bla,bla,bla...


Título: Re: Ayuda con Copiador de USB
Publicado por: Serapis en 14 Febrero 2017, 18:04 pm
bla,bla,bla...


Título: Re: Ayuda con Copiador de USB
Publicado por: Eleкtro en 27 Febrero 2017, 15:39 pm
Hola.

La siguiente solución que voy a compartir es de forma gratuita pero también se puede encontrar junto a muchas otras diversas utilidades imprescindibles (must-have!) en mi framework de pago Elektrokit, el cual se encuentra a la venta por un módico precio en el mercado web de CodeCanyon, en Envato.

Bien. Primero empecemos con los miembros que compondrian el algoritmo que se suscribe a los eventos de inserción y extracción de dispositivos extraibles; la lógica de todo ello lo encapsulé en un tipo bautizado con el nombre DriveWatcher y cuyo modo de empleo es orientado a eventos, muy sencillo de manejar...

Simplemente tienes que copiar y pegar estas clases en tu proyecto:

DriveWatcher.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-December-2016
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' New()
  11.  
  12. #End Region
  13.  
  14. #Region " Events "
  15.  
  16. ' DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)
  17.  
  18. #End Region
  19.  
  20. #Region " Properties "
  21.  
  22. ' Drives As IEnumerable(Of DriveInfo)
  23. ' Handle As IntPtr
  24. ' IsRunning As Boolean
  25.  
  26. #End Region
  27.  
  28. #Region " Methods "
  29.  
  30. ' Start()
  31. ' Stop()
  32.  
  33. #End Region
  34.  
  35. #End Region
  36.  
  37. #Region " Usage Examples "
  38.  
  39. #End Region
  40.  
  41. #Region " Option Statements "
  42.  
  43. Option Strict On
  44. Option Explicit On
  45. Option Infer Off
  46.  
  47. #End Region
  48.  
  49. #Region " Imports "
  50.  
  51. Imports WindowsApplication1.IO.Types.EventArgs
  52. Imports WindowsApplication1.Win32.Enums
  53. Imports WindowsApplication1.Win32.Types
  54.  
  55. ' Imports Elektro.Core.Types
  56. ' Imports Elektro.Core.IO.Types.EventArgs
  57. ' Imports Elektro.Interop.Win32.Enums
  58. ' Imports Elektro.Interop.Win32.Types
  59.  
  60. #End Region
  61.  
  62. #Region " Drive Watcher "
  63.  
  64. Namespace IO.Types
  65.  
  66.    ''' ----------------------------------------------------------------------------------------------------
  67.    ''' <summary>
  68.    ''' A device insertion and removal monitor.
  69.    ''' </summary>
  70.    ''' ----------------------------------------------------------------------------------------------------
  71.    ''' <example> This is a code example.
  72.    ''' <code>
  73.    ''' </code>
  74.    ''' </example>
  75.    ''' ----------------------------------------------------------------------------------------------------
  76.    Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable ' : Inherits AestheticNativeWindow
  77.  
  78. #Region " Properties "
  79.  
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <summary>
  82.        ''' Gets the connected drives on this computer.
  83.        ''' </summary>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        Public Overridable ReadOnly Property Drives As IEnumerable(Of DriveInfo)
  86.            <DebuggerStepThrough>
  87.            Get
  88.                Return DriveInfo.GetDrives
  89.            End Get
  90.        End Property
  91.  
  92.        ''' ----------------------------------------------------------------------------------------------------
  93.        ''' <summary>
  94.        ''' Gets a value that determines whether the monitor is running.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Public Overridable ReadOnly Property IsRunning As Boolean
  98.            <DebuggerStepThrough>
  99.            Get
  100.                Return Me.isRunningB
  101.            End Get
  102.        End Property
  103.        Protected isRunningB As Boolean
  104.  
  105.        ''' ----------------------------------------------------------------------------------------------------
  106.        ''' <summary>
  107.        ''' Gets the handle for the <see cref="NativeWindow"/> that owns this <see cref="DriveWatcher"/> instance.
  108.        ''' </summary>
  109.        ''' ----------------------------------------------------------------------------------------------------
  110.        ''' <value>
  111.        ''' The handle.
  112.        ''' </value>
  113.        ''' ----------------------------------------------------------------------------------------------------
  114.        Public Overridable Shadows ReadOnly Property Handle As IntPtr
  115.            Get
  116.                Return MyBase.Handle
  117.            End Get
  118.        End Property
  119.  
  120. #End Region
  121.  
  122. #Region " Enumerations "
  123.  
  124.        ''' ----------------------------------------------------------------------------------------------------
  125.        ''' <summary>
  126.        ''' Specifies a computer device type.
  127.        ''' </summary>
  128.        ''' ----------------------------------------------------------------------------------------------------
  129.        ''' <remarks>
  130.        ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363246%28v=vs.85%29.aspx"/>
  131.        ''' </remarks>
  132.        ''' ----------------------------------------------------------------------------------------------------
  133.        Private Enum DeviceType As Integer
  134.  
  135.            ' *****************************************************************************
  136.            '                            WARNING!, NEED TO KNOW...
  137.            '
  138.            '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS API
  139.            ' *****************************************************************************
  140.  
  141.            ''' <summary>
  142.            ''' Logical volume.
  143.            ''' </summary>
  144.            Logical = &H2
  145.  
  146.        End Enum
  147.  
  148. #End Region
  149.  
  150. #Region " Events "
  151.  
  152.        ''' ----------------------------------------------------------------------------------------------------
  153.        ''' <summary>
  154.        ''' A list of event delegates.
  155.        ''' </summary>
  156.        ''' ----------------------------------------------------------------------------------------------------
  157.        Private ReadOnly events As EventHandlerList
  158.  
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        ''' <summary>
  161.        ''' Occurs when a drive is inserted, removed, or changed.
  162.        ''' </summary>
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        Public Custom Event DriveStatusChanged As EventHandler(Of DriveStatusChangedEventArgs)
  165.  
  166.            <DebuggerNonUserCode>
  167.            <DebuggerStepThrough>
  168.            AddHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
  169.                Me.events.AddHandler("DriveStatusChangedEvent", value)
  170.            End AddHandler
  171.  
  172.            <DebuggerNonUserCode>
  173.            <DebuggerStepThrough>
  174.            RemoveHandler(ByVal value As EventHandler(Of DriveStatusChangedEventArgs))
  175.                Me.events.RemoveHandler("DriveStatusChangedEvent", value)
  176.            End RemoveHandler
  177.  
  178.            <DebuggerNonUserCode>
  179.            <DebuggerStepThrough>
  180.            RaiseEvent(ByVal sender As Object, ByVal e As DriveStatusChangedEventArgs)
  181.                Dim handler As EventHandler(Of DriveStatusChangedEventArgs) =
  182.                    DirectCast(Me.events("DriveStatusChangedEvent"), EventHandler(Of DriveStatusChangedEventArgs))
  183.  
  184.                If (handler IsNot Nothing) Then
  185.                    handler.Invoke(sender, e)
  186.                End If
  187.            End RaiseEvent
  188.  
  189.        End Event
  190.  
  191. #End Region
  192.  
  193. #Region " Event Invocators "
  194.  
  195.        ''' ----------------------------------------------------------------------------------------------------
  196.        ''' <summary>
  197.        ''' Raises <see cref="DriveStatusChanged"/> event.
  198.        ''' </summary>
  199.        ''' ----------------------------------------------------------------------------------------------------
  200.        ''' <param name="e">
  201.        ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
  202.        ''' </param>
  203.        ''' ----------------------------------------------------------------------------------------------------
  204.        <DebuggerStepThrough>
  205.        Protected Overridable Sub OnDriveStatusChanged(ByVal e As DriveStatusChangedEventArgs)
  206.  
  207.            RaiseEvent DriveStatusChanged(Me, e)
  208.  
  209.        End Sub
  210.  
  211. #End Region
  212.  
  213. #Region " Constructors "
  214.  
  215.        ''' ----------------------------------------------------------------------------------------------------
  216.        ''' <summary>
  217.        ''' Initializes a new instance of <see cref="DriveWatcher"/> class.
  218.        ''' </summary>
  219.        ''' ----------------------------------------------------------------------------------------------------
  220.        <DebuggerStepThrough>
  221.        Public Sub New()
  222.            Me.events = New EventHandlerList
  223.        End Sub
  224.  
  225. #End Region
  226.  
  227. #Region " Public Methods "
  228.  
  229.        ''' ----------------------------------------------------------------------------------------------------
  230.        ''' <summary>
  231.        ''' Starts monitoring.
  232.        ''' </summary>
  233.        ''' ----------------------------------------------------------------------------------------------------
  234.        ''' <exception cref="Exception">
  235.        ''' Monitor is already running.
  236.        ''' </exception>
  237.        ''' ----------------------------------------------------------------------------------------------------
  238.        <DebuggerStepThrough>
  239.        Public Overridable Sub Start()
  240.  
  241.            If (Me.Handle = IntPtr.Zero) Then
  242.                MyBase.CreateHandle(New CreateParams())
  243.                Me.isRunningB = True
  244.  
  245.            Else
  246.                Throw New Exception(message:="Monitor is already running.")
  247.  
  248.            End If
  249.  
  250.        End Sub
  251.  
  252.        ''' ----------------------------------------------------------------------------------------------------
  253.        ''' <summary>
  254.        ''' Stops monitoring.
  255.        ''' </summary>
  256.        ''' ----------------------------------------------------------------------------------------------------
  257.        ''' <exception cref="Exception">
  258.        ''' Monitor is already stopped.
  259.        ''' </exception>
  260.        ''' ----------------------------------------------------------------------------------------------------
  261.        <DebuggerStepThrough>
  262.        Public Overridable Sub [Stop]()
  263.  
  264.            If (Me.Handle <> IntPtr.Zero) Then
  265.                Me.isRunningB = False
  266.                MyBase.DestroyHandle()
  267.  
  268.            Else
  269.                Throw New Exception(message:="Monitor is already stopped.")
  270.  
  271.            End If
  272.  
  273.        End Sub
  274.  
  275. #End Region
  276.  
  277. #Region " Private Methods "
  278.  
  279.        ''' ----------------------------------------------------------------------------------------------------
  280.        ''' <summary>
  281.        ''' Gets the drive letter stored in a <see cref="DevBroadcastVolume"/> structure.
  282.        ''' </summary>
  283.        ''' ----------------------------------------------------------------------------------------------------
  284.        ''' <param name="device">
  285.        ''' The <see cref="DevBroadcastVolume"/> structure containing the device mask.
  286.        ''' </param>
  287.        ''' ----------------------------------------------------------------------------------------------------
  288.        ''' <returns>
  289.        ''' The drive letter.
  290.        ''' </returns>
  291.        ''' ----------------------------------------------------------------------------------------------------
  292.        <DebuggerStepThrough>
  293.        Protected Overridable Function GetDriveLetter(ByVal device As DevBroadcastVolume) As Char
  294.  
  295.            Dim driveLetters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
  296.  
  297.            Dim deviceID As New BitArray(BitConverter.GetBytes(device.Mask))
  298.  
  299.            For i As Integer = 0 To deviceID.Length
  300.  
  301.                If deviceID(i) Then
  302.                    Return driveLetters(i)
  303.                End If
  304.  
  305.            Next i
  306.  
  307.            Return Nothing
  308.  
  309.        End Function
  310.  
  311. #End Region
  312.  
  313. #Region " Window Procedure (WndProc) "
  314.  
  315.        ''' ----------------------------------------------------------------------------------------------------
  316.        ''' <summary>
  317.        ''' Invokes the default window procedure associated with this window to process windows messages.
  318.        ''' </summary>
  319.        ''' ----------------------------------------------------------------------------------------------------
  320.        ''' <param name="m">
  321.        ''' A <see cref="Message"/> that is associated with the current Windows message.
  322.        ''' </param>
  323.        ''' ----------------------------------------------------------------------------------------------------
  324.        <DebuggerStepThrough>
  325.        Protected Overrides Sub WndProc(ByRef m As Message)
  326.  
  327.            Select Case m.Msg
  328.  
  329.                Case DeviceEvents.Change ' The hardware has changed.
  330.  
  331.                    If (m.LParam = IntPtr.Zero) Then
  332.                        Exit Select
  333.                    End If
  334.  
  335.                    ' If it's an storage device then...
  336.                    If Marshal.ReadInt32(m.LParam, 4) = DeviceType.Logical Then
  337.  
  338.                        ' Transform the LParam pointer into the data structure.
  339.                        Dim currentWDrive As DevBroadcastVolume =
  340.                            DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DevBroadcastVolume)), DevBroadcastVolume)
  341.  
  342.                        Dim driveLetter As Char = Me.GetDriveLetter(currentWDrive)
  343.                        Dim deviceEvent As DeviceEvents = DirectCast(m.WParam.ToInt32, DeviceEvents)
  344.                        Dim driveInfo As New DriveInfo(driveLetter)
  345.  
  346.                        Me.OnDriveStatusChanged(New DriveStatusChangedEventArgs(deviceEvent, driveInfo))
  347.  
  348.                    End If
  349.  
  350.            End Select
  351.  
  352.            ' Return Message to base message handler.
  353.            MyBase.WndProc(m)
  354.  
  355.        End Sub
  356.  
  357. #End Region
  358.  
  359. #Region " IDisposable Implementation "
  360.  
  361.        ''' ----------------------------------------------------------------------------------------------------
  362.        ''' <summary>
  363.        ''' Flag to detect redundant calls when disposing.
  364.        ''' </summary>
  365.        ''' ----------------------------------------------------------------------------------------------------
  366.        Private isDisposed As Boolean
  367.  
  368.        ''' ----------------------------------------------------------------------------------------------------
  369.        ''' <summary>
  370.        ''' Releases all the resources used by this instance.
  371.        ''' </summary>
  372.        ''' ----------------------------------------------------------------------------------------------------
  373.        <DebuggerStepThrough>
  374.        Public Sub Dispose() Implements IDisposable.Dispose
  375.  
  376.            Me.Dispose(isDisposing:=True)
  377.            GC.SuppressFinalize(obj:=Me)
  378.  
  379.        End Sub
  380.  
  381.        ''' ----------------------------------------------------------------------------------------------------
  382.        ''' <summary>
  383.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  384.        ''' Releases unmanaged and, optionally, managed resources.
  385.        ''' </summary>
  386.        ''' ----------------------------------------------------------------------------------------------------
  387.        ''' <param name="isDisposing">
  388.        ''' <see langword="True"/>  to release both managed and unmanaged resources;
  389.        ''' <see langword="False"/> to release only unmanaged resources.
  390.        ''' </param>
  391.        ''' ----------------------------------------------------------------------------------------------------
  392.        <DebuggerStepThrough>
  393.        Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  394.  
  395.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  396.                Me.events.Dispose()
  397.                If Me.isRunningB Then
  398.                    Me.Stop()
  399.                End If
  400.            End If
  401.  
  402.            Me.isDisposed = True
  403.  
  404.        End Sub
  405.  
  406. #End Region
  407.  
  408.    End Class
  409.  
  410. End Namespace
  411.  
  412. #End Region
  413.  

DriveStatusChangedEventArgs.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 10-November-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' New(DeviceEvents, DriveInfo)
  11.  
  12. #End Region
  13.  
  14. #Region " Properties "
  15.  
  16. ' DeviceEvent As DriveWatcher.DeviceEvents
  17. ' DriveInfo As DriveInfo
  18.  
  19. #End Region
  20.  
  21. #End Region
  22.  
  23. #Region " Option Statements "
  24.  
  25. Option Strict On
  26. Option Explicit On
  27. Option Infer Off
  28.  
  29. #End Region
  30.  
  31. #Region " Imports "
  32.  
  33. Imports WindowsApplication1.Win32.Enums
  34.  
  35. ' Imports Elektro.Core.Types
  36. ' Imports Elektro.Interop.Win32.Enums
  37.  
  38. #End Region
  39.  
  40. #Region " DriveStatusChanged EventArgs "
  41.  
  42. Namespace IO.Types.EventArgs
  43.  
  44.    ''' ----------------------------------------------------------------------------------------------------
  45.    ''' <summary>
  46.    ''' Contains the event-data of a <see cref="DriveWatcher.DriveStatusChanged"/> event.
  47.    ''' </summary>
  48.    ''' ----------------------------------------------------------------------------------------------------
  49.    Public NotInheritable Class DriveStatusChangedEventArgs : Inherits System.EventArgs ' : Inherits AestheticEventArgs
  50.  
  51. #Region " Properties "
  52.  
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <summary>
  55.        ''' Gets the device event that occurred.
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <value>
  59.        ''' The drive info.
  60.        ''' </value>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        Public ReadOnly Property DeviceEvent As DeviceEvents
  63.            <DebuggerStepThrough>
  64.            Get
  65.                Return Me.deviceEventsB
  66.            End Get
  67.        End Property
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        ''' <summary>
  70.        ''' ( Backing field )
  71.        ''' The device event that occurred.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        Private ReadOnly deviceEventsB As DeviceEvents
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Gets the drive info.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <value>
  82.        ''' The drive info.
  83.        ''' </value>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        Public ReadOnly Property DriveInfo As DriveInfo
  86.            <DebuggerStepThrough>
  87.            Get
  88.                Return Me.driveInfoB
  89.            End Get
  90.        End Property
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        ''' <summary>
  93.        ''' ( Backing field )
  94.        ''' The drive info.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Private ReadOnly driveInfoB As DriveInfo
  98.  
  99. #End Region
  100.  
  101. #Region " Constructors "
  102.  
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <summary>
  105.        ''' Prevents a default instance of the <see cref="DriveStatusChangedEventArgs"/> class from being created.
  106.        ''' </summary>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        <DebuggerNonUserCode>
  109.        Private Sub New()
  110.        End Sub
  111.  
  112.        ''' ----------------------------------------------------------------------------------------------------
  113.        ''' <summary>
  114.        ''' Initializes a new instance of the <see cref="DriveStatusChangedEventArgs"/> class.
  115.        ''' </summary>
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <param name="driveInfo">
  118.        ''' The drive info.
  119.        ''' </param>
  120.        ''' ----------------------------------------------------------------------------------------------------
  121.        <DebuggerStepThrough>
  122.        Public Sub New(ByVal deviceEvent As DeviceEvents, ByVal driveInfo As DriveInfo)
  123.  
  124.            Me.deviceEventsB = deviceEvent
  125.            Me.driveInfoB = driveInfo
  126.  
  127.        End Sub
  128.  
  129. #End Region
  130.  
  131.    End Class
  132.  
  133. End Namespace
  134.  
  135. #End Region
  136.  

DeviceEvents.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 10-November-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Device Events "
  15.  
  16. Namespace Win32.Enums
  17.  
  18.    ''' ----------------------------------------------------------------------------------------------------
  19.    ''' <summary>
  20.    ''' Specifies a change to the hardware configuration of a device.
  21.    ''' </summary>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <remarks>
  24.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx"/>
  25.    ''' <para></para>
  26.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx"/>
  27.    ''' </remarks>
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    Public Enum DeviceEvents As Integer
  30.  
  31.        ' *****************************************************************************
  32.        '                            WARNING!, NEED TO KNOW...
  33.        '
  34.        '  THIS ENUMERATION IS PARTIALLY DEFINED TO MEET THE PURPOSES OF THIS API
  35.        ' *****************************************************************************
  36.  
  37.        ''' <summary>
  38.        ''' The current configuration has changed, due to a dock or undock.
  39.        ''' </summary>
  40.        Change = &H219
  41.  
  42.        ''' <summary>
  43.        ''' A device or piece of media has been inserted and becomes available.
  44.        ''' </summary>
  45.        Arrival = &H8000
  46.  
  47.        ''' <summary>
  48.        ''' Request permission to remove a device or piece of media.
  49.        ''' <para></para>
  50.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  51.        ''' However, any application can deny this request and cancel the operation.
  52.        ''' </summary>
  53.        QueryRemove = &H8001
  54.  
  55.        ''' <summary>
  56.        ''' A request to remove a device or piece of media has been canceled.
  57.        ''' </summary>
  58.        QueryRemoveFailed = &H8002
  59.  
  60.        ''' <summary>
  61.        ''' A device or piece of media is being removed and is no longer available for use.
  62.        ''' </summary>
  63.        RemovePending = &H8003
  64.  
  65.        ''' <summary>
  66.        ''' A device or piece of media has been removed.
  67.        ''' </summary>
  68.        RemoveComplete = &H8004
  69.  
  70.    End Enum
  71.  
  72. End Namespace
  73.  
  74. #End Region
  75.  

DevBroadcastVolume.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 10-November-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports System.Runtime.InteropServices
  17.  
  18. #End Region
  19.  
  20. #Region " DevBroadcast Volume "
  21.  
  22. Namespace Win32.Types
  23.  
  24.    ''' ----------------------------------------------------------------------------------------------------
  25.    ''' <summary>
  26.    ''' Contains information about a logical volume.
  27.    ''' </summary>
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    ''' <remarks>
  30.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx"/>
  31.    ''' </remarks>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    <DebuggerStepThrough>
  34.    <StructLayout(LayoutKind.Sequential)>
  35.    Public Structure DevBroadcastVolume
  36.  
  37.        ''' ----------------------------------------------------------------------------------------------------
  38.        ''' <summary>
  39.        ''' The size of this structure, in bytes.
  40.        ''' </summary>
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        Public Size As UInteger
  43.  
  44.        ''' ----------------------------------------------------------------------------------------------------
  45.        ''' <summary>
  46.        ''' Set to DBT_DEVTYP_VOLUME (2).
  47.        ''' </summary>
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        Public Type As UInteger
  50.  
  51.        ''' ----------------------------------------------------------------------------------------------------
  52.        ''' <summary>
  53.        ''' Reserved parameter; do not use this.
  54.        ''' </summary>
  55.        ''' ----------------------------------------------------------------------------------------------------
  56.        Public Reserved As UInteger
  57.  
  58.        ''' ----------------------------------------------------------------------------------------------------
  59.        ''' <summary>
  60.        ''' The logical unit mask identifying one or more logical units.
  61.        ''' Each bit in the mask corresponds to one logical drive.
  62.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  63.        ''' </summary>
  64.        ''' ----------------------------------------------------------------------------------------------------
  65.        Public Mask As UInteger
  66.  
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        ''' <summary>
  69.        ''' This parameter can be one of the following values:
  70.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  71.        ''' '0x0002': Indicated logical volume is a network volume.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        Public Flags As UShort
  75.  
  76.    End Structure
  77.  
  78. End Namespace
  79.  
  80. #End Region
  81.  



Por último, esto de aquí abajo seria uno de los posibles algoritmos que se podría elaborar para el copiado de archivos. Para llevarlo a cabo simplemente he reciclado y adaptado el código que ya te enseñé en este otro post:
  • http://foro.elhacker.net/net/ayuda_con_un_contador-t464137.0.html;msg2106079#msg2106079
...por eso lo he dejado tan "en bruto" y con lineas comentadas, para denotar las diferencias entre uno y otro código.

Código
  1. Imports System
  2. Imports WindowsApplication1.IO.Types
  3. Imports WindowsApplication1.IO.Types.EventArgs
  4.  
  5. Public NotInheritable Class Form1 : Inherits Form
  6.  
  7.    Friend WithEvents DriveMon As New DriveWatcher()
  8.    Private ReadOnly outDir As String = "C:\Monitor\"
  9.  
  10.    ''' ----------------------------------------------------------------------------------------------------
  11.    ''' <summary>
  12.    ''' Handles the <see cref="DriveWatcher.DriveStatusChanged"/> event of the <see cref="DriveMon"/> instance.
  13.    ''' </summary>
  14.    ''' ----------------------------------------------------------------------------------------------------
  15.    ''' <param name="sender">
  16.    ''' The source of the event.
  17.    ''' </param>
  18.    '''
  19.    ''' <param name="e">
  20.    ''' The <see cref="DriveStatusChangedEventArgs"/> instance containing the event data.
  21.    ''' </param>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    Private Sub DriveMon_DriveStatusChanged(ByVal sender As Object, ByVal e As DriveStatusChangedEventArgs) Handles DriveMon.DriveStatusChanged
  24.  
  25.        Select Case e.DeviceEvent
  26.  
  27.            Case Win32.Enums.DeviceEvents.Arrival
  28.                Dim sb As New StringBuilder
  29.                With sb
  30.                    .AppendLine("New drive connected...'")
  31.                    .AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
  32.                    .AppendLine(String.Format("Root.: {0}", e.DriveInfo.RootDirectory))
  33.                    .AppendLine(String.Format("Label: {0}", e.DriveInfo.VolumeLabel))
  34.                    .AppendLine(String.Format("Size.: {0} GB", (e.DriveInfo.TotalSize / (1024 ^ 3)).ToString("n1")))
  35.                End With
  36.                Console.WriteLine(sb.ToString())
  37.                Console.WriteLine("Initializing copy...")
  38.  
  39.                Dim copyTask As Task(Of Integer) = Me.CopyFiles(e.DriveInfo.VolumeLabel, e.DriveInfo.RootDirectory.FullName, outDir)
  40.                ' Await Task.WhenAll(copyTask)
  41.  
  42.            Case Win32.Enums.DeviceEvents.RemoveComplete
  43.                Dim sb As New StringBuilder
  44.                With sb
  45.                    .AppendLine("Drive disconnected...'")
  46.                    .AppendLine(String.Format("Name: {0}", e.DriveInfo.Name))
  47.                    sb.AppendLine(String.Format("Root: {0}", e.DriveInfo.RootDirectory))
  48.                End With
  49.                Console.WriteLine(sb.ToString())
  50.  
  51.        End Select
  52.  
  53.    End Sub
  54.  
  55.    Private Sub StartMon_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_StartMon.Click
  56.        Me.DriveMon.Start()
  57.    End Sub
  58.  
  59.    Private Sub StopMon_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button_StopMon.Click
  60.        Me.DriveMon.Stop()
  61.    End Sub
  62.  
  63.    Public Async Function CopyFiles(ByVal labelName As String, ByVal srcDirPath As String, ByVal dstDirPath As String) As Task(Of Integer)
  64.  
  65.        Dim filesDict As New Dictionary(Of FileInfo, FileInfo) ' {[Key: Source File], [Value: Destination File]}
  66.  
  67.        For Each file As FileInfo In New DirectoryInfo(srcDirPath).EnumerateFiles("*", SearchOption.AllDirectories)
  68.            Dim srcRoot As String = file.Directory.Root.FullName
  69.            Dim dstFilepath As String = file.FullName.Replace(srcRoot, Path.Combine(Me.outDir, labelName) & "\")
  70.            filesDict.Add(file, New FileInfo(dstFilepath))
  71.        Next file
  72.  
  73.        ' Dim maxFileCount As Integer = filesDict.Count()
  74.        ' Dim curFileCount As Integer
  75.  
  76.        ' Dim updateLabelCallback As New SendOrPostCallback(
  77.        '     Sub(ByVal state As Object)
  78.        '         progressCtrl.Text = String.Format("{0} of {1} files copied...", CInt(state), maxFileCount)
  79.        '     End Sub)
  80.  
  81.        Dim copySingleFileAction As New Action(Of KeyValuePair(Of FileInfo, FileInfo))(
  82.            Sub(ByVal pair As KeyValuePair(Of FileInfo, FileInfo))
  83.                Try
  84.                    If Not (pair.Value.Directory.Exists) Then
  85.                        pair.Value.Directory.Create()
  86.                    End If
  87.                    pair.Key.CopyTo(pair.Value.FullName, overwrite:=False)
  88.                    ' SynchronizationContext.Current.Post(updateLabelCallback, Interlocked.Increment(curFileCount))
  89.                Catch ex As Exception
  90.                End Try
  91.            End Sub)
  92.  
  93.        Dim copyAllFilesFunc As Func(Of Integer) =
  94.            Function() As Integer
  95.                ' Parallel.ForEach(Of KeyValuePair(Of FileInfo, FileInfo))(filesDict, copySingleFileAction)
  96.                ' -- Sin paralelismo en este caso es más eficiente.
  97.                For Each pair As KeyValuePair(Of FileInfo, FileInfo) In filesDict
  98.                    copySingleFileAction(pair)
  99.                Next
  100.                ' Return curFileCount ' Return the amount of files that were copied.
  101.            End Function
  102.  
  103.        If Not New DirectoryInfo(dstDirPath).Exists Then
  104.            Directory.CreateDirectory(dstDirPath, Nothing)
  105.        End If
  106.  
  107.        Dim t As New Task(Of Integer)(copyAllFilesFunc, TaskCreationOptions.LongRunning)
  108.        t.Start()
  109.        Await t
  110.  
  111.        Return t.Result
  112.    End Function
  113.  
  114. End Class

De esa manera, se ejecutará de forma automática y asíncrona una tarea que iniciará el copiado de archivos por cada dispositivo extraible de almacenamiento que insertes en el PC en cuestión. Los archivos se copiarán del USB a la carpeta destino especificada, conservando la estructura de directorios de la ruta del archivo de origen a copiar. Si extraes un USB durante una operación de copiado, simplemente se disparará una excepción controlada que ignorará el copiado, y podrás reinsertar el mismo USB para seguir la copia, o insertar un nuevo USB. Puedes ocupar varias ranuras de USB de forma simultanea para copair varios dispositivos al mismo tiempo. Y creo que no me dejo nada destacable por mencionar sobre la funcionalidad del código.

Cabe mencionar que el código no está optimizado, tan solo es un ejemplo básico pero funcional para lograr lo que quieres, pues no voy a ponerme a hacerte yo todo el trabajo y escribir aquí la de Dios. Te recomiendo añadir controles de errores al menos para evaluar los permisos de usuario de la carpeta destino, además también podrías habilitar la capacidad de poder cancelar al instante una operación de copiado que esté en curso al momento de extraer un dispositivo USB, esto lo harias mediante el la creación y el uso de un token de cancelación el cual lo pasarías como argumento a una de las sobrecargas del método Task.Start(), y evaluarias una petición de cancelación en el bloque del método CopyFiles del código que te mostré. Otra cosa que se puede mejorar es el orden de iteración/copiado de archivos, podrías ordenar la colección para que se procesen los archivos de menor tamaño a mayor, dependiendo de tus necesidades.
En fin, puedes improvisar ese código de ejemplo de mil maneras distintas para perfeccionarlo.

¡Saludos!


Título: Re: Ayuda con Copiador de USB
Publicado por: Serapis en 20 Abril 2017, 01:55 am
Curiosamente encontré que el VBTeam (el equipo de visual Basic), en su página han hablado de esto (hace apenas una semana), parece como si nos hubieran leído...

Aportan algunas soluciones más, que aunque óptimas, creo que son más complicadas para usuarios noveles. Vale la pena hecharles un vistazo:
https://blogs.msdn.microsoft.com/vbteam/2017/04/10/easy-async-and-await-for-vbs-part-1-or/

...es la parte 1, o sea que posiblemente vuelvan en otro momento a retomar el tema...


Título: Re: Ayuda con Copiador de USB
Publicado por: Maurice_Lupin en 22 Abril 2017, 20:07 pm
Buenos codigos, voy a experimentar con ellos para hacer bromas a mis amigos, sólo que en lugar de copiar será cortar :xD

Saludos.