Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# drag and drop files to form

How could I load files to a form by drag-and-drop?

Which event will appear?

Which component should I use?

And how to determine name of file and others properties after drag-and-dropping it to a form?

Thank you!

Code

   private void panel1_DragEnter(object sender, DragEventsArgs e){
        if (e.Data.GetDataPresent(DataFormats.Text)){
              e.Effect = DragDropEffects.Move;
              MessageBox.Show(e.Data.GetData(DataFormats.Text).toString());
        }
        if (e.Data.GetDataPresent(DataFormats.FileDrop)){

        }
   }

ok, this works.

How about files? How can I get filename and extension?

and this is only a dragEnter action.

like image 537
gaussblurinc Avatar asked Dec 18 '11 09:12

gaussblurinc


2 Answers

This code will loop through and print the full names (including extensions) of all the files dragged into your window:

if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string filePath in files) 
      {
          Console.WriteLine(filePath);
      }
}
like image 113
Sarwar Erfan Avatar answered Sep 20 '22 13:09

Sarwar Erfan


Check the below link for more info

http://doitdotnet.wordpress.com/2011/12/18/drag-and-drop-files-into-winforms/

private void Form2_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());
          }
    }
}
like image 20
TechsnippetsOnline Avatar answered Sep 20 '22 13:09

TechsnippetsOnline