Drag & drop and get file path in VB.NET

This is just a note to state that if drag and drop does not work, it could be because you are running Visual Studio in Administrator Mode (Windows 7 and up I believe).

This also has to do with the UAC level currently set on your Windows installation.


It's quite easy. Just enable drap-and-drop by setting the AllowDrop property to True and handle the DragEnter and DragDrop events.

In the DragEnter event handler, you can check if the data is of the type you want using the DataFormats class.

In the DragDrop event handler, use the Data property of the DragEventArgs to receive the actual data and the GetData method


Example:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Me.AllowDrop = True
End Sub

Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
    Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
    For Each path In files
        MsgBox(path)
    Next
End Sub

Private Sub Form1_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub