DotNetCurry Logo

Drag and Drop Text Files from Windows Explorer to your Windows Form Application

Posted by: Suprotim Agarwal , on 8/24/2008, in Category WinForms & WinRT
Views: 74113
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.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by alex on Tuesday, September 9, 2008 5:07 AM
Nice! Good to see the .NET platform mostly succeeds at keeping things simple.
Comment posted by alex on Tuesday, September 9, 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 9, 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 8, 2010 9:00 AM
really heplful
Comment posted by v2011 on Thursday, June 16, 2011 12:30 PM
Hello

I trying to display a message box in DragDrop event as shown is this example. After i Drag the file and Drop the file, it locks the source (Desktop or Windows Explorer). Can you tell me how i can resolve this issue?

Thanks
v2011
Comment posted by v2011 on Thursday, June 16, 2011 12:33 PM
Hello

I trying to display a message box in DragDrop event as shown is this example. After i Drag the file and Drop the file, it locks the source (Desktop or Windows Explorer). Can you tell me how i can resolve this issue?

Thanks
v2011
Comment posted by Dave on Friday, April 12, 2013 11:29 AM
Too bad this code as written (copied verbatim) does not work at all in Windows 7.
Comment posted by anonymous on Wednesday, September 25, 2013 2:08 PM
Awesome article.
Thanks so much!
Helped me with my application.
Comment posted by Adam on Saturday, March 7, 2015 7:38 AM
@v2011 It locks it because the file stream has not been closed.
Add tr.Close(); to the end of the dragdrop event