Create new account I forgot my password    

Drag and Drop Text Files from Windows Explorer to your Windows Form Application
Rating: 10 user(s) have rated this article Average rating: 4.0
Posted by: Suprotim Agarwal, on 8/24/2008, in category "Windows Forms 2.0"
Views: this article has been read 21711 times
Abstract: This is a short article describing how you can drag and drop files from your Desktop/Windows Explorer to your Windows Form application. In this article, we will drag text files from the desktop and drop it on our WinForm application, to display the contents of the text files.

Drag and Drop Text Files from Windows Explorer to your Windows Form Application
 
This is a short article describing how you can drag and drop files from your Desktop/Windows Explorer to your Windows Form application. In this article, we will drag text files from the desktop and drop it on our WinForm application, to display the contents of the text files. Let us see the steps required to do so:
Step 1: Open Visual Studio > File > New > Project. In the Project Types pane, choose the language of your choice (Visual C# or Visual Basic). In the Templates pane, choose Windows Application. Choose a name and location for the project and click OK.
Step 2: To set up the functionality for the drag drop operation, let us take a quick overview of the steps involved to do so. Let us assume that this WinForm application is ready and is running. The user will select one or more text files on the desktop or Windows Explorer. The user will then drag the selected files kept on the desktop, on to the running application form. The contents of all the text files will then be displayed in the application. To complete the operation, the following events need to be handled.
Form DragEnter Event – this event will be handled when the file is dragged into the Form’s bounds.
Form DragDrop Event - Occurs when a drag-and-drop operation is completed.
Step 3: In the form load event, register the events for the drag drop operation as shown below. Notice that the ‘AllowDrop’ property has to be set to true to be able to drop items on the form:
C#
private void Form1_Load(object sender, EventArgs e)
{
    this.AllowDrop = true;
    this.DragEnter += Form1_DragEnter;
    this.DragDrop += Form1_DragDrop;
}
VB.NET
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
      Me.AllowDrop = True
      Me.DragEnter += Form1_DragEnter
      Me.DragDrop += Form1_DragDrop
End Sub
Step 4: Moving ahead, we will now add code to the respective events discussed above:
C#
private void Form1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}
 
private void Form1_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
        foreach (string fileLoc in filePaths)
        {
            // Code to read the contents of the text file
            if (File.Exists(fileLoc))
            {
                using (TextReader tr = new StreamReader(fileLoc))
                {
                    MessageBox.Show(tr.ReadToEnd());
                }
            }
 
        }
    }
}
VB.NET
Private Sub Form1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs)
      If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
      Else
            e.Effect = DragDropEffects.None
      End If
End Sub
 
Private Sub Form1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)
      If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
            For Each fileLoc As String In filePaths
                  ' Code to read the contents of the text file
                  If File.Exists(fileLoc) Then
                        Using tr As TextReader = New StreamReader(fileLoc)
                              MessageBox.Show(tr.ReadToEnd())
                        End Using
                  End If
 
            Next fileLoc
      End If
End Sub
In the Form1_DragEnter we use the DataFormats.FileDrop field to interact with shell file drags, when a drag-and-drop operation occurs. This method is called before GetData().
Finally in the Form1_DragDrop, we will extract the file path(s) using the GetDate() method in a string array. So if two text files are dragged from the desktop to the application, the string array will contain two file paths. The last step is to loop through the file paths and use the StreamReader to read the contents of the text file.
That’s it. Run the sample and you will be able to perform drag drop operations from the desktop/Windows Explorer to the running application form. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by alex on Tuesday, September 09, 2008 5:07 AM
Nice! Good to see the .NET platform mostly succeeds at keeping things simple.
Comment posted by alex on Tuesday, September 09, 2008 5:07 AM
Nice! Good to see the .NET platform mostly succeeds at keeping things simple.
Comment posted by Suprotim Agarwal on Tuesday, September 09, 2008 9:30 PM
Alex: Yep, can't agree more!!
Comment posted by praveen on Monday, September 15, 2008 3:44 PM
good code.....
Comment posted by Arabinda on Thursday, November 20, 2008 1:14 AM
Is there any way to implement the same feature in ASP.NET application ?
Comment posted by Suprotim Agarwal on Thursday, November 20, 2008 10:26 PM
Arabinda: You will have to use an ActiveX control or a third party control to do so.
Comment posted by Quakeboy on Sunday, January 11, 2009 1:43 AM
Great article.. very useful
Comment posted by winforms n00b on Friday, August 14, 2009 5:21 AM
The code doesn't work.

Me.DragEnter += Form1_DragEnter <- this line produces an error and says use RaiseEvent instead

There are other erros too...
Comment posted by Suprotim Agarwal on Saturday, August 15, 2009 2:41 AM
Are you using WinForms 2.0? Post the code that causes error or mail me the project using the Contact page
Comment posted by Pat on Thursday, August 27, 2009 5:46 PM
Great article, however, does not work for me either.  I am building this in C# using .net 3.5. When I drag the files over I get the "not here" cursor  Any ideas?
Comment posted by Sathish Kumar on Wednesday, November 11, 2009 3:06 AM
Hi

The above code works fine..

How to Drag and Drop any format Files from Desktop/Windows Explorer to the treeview in Windows Form Application..

can u pls give me the solution.

thanks & regards
M.Sathish Kumar
Comment posted by varun on Thursday, April 08, 2010 9:00 AM
really heplful

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER