1

How can I capture the file extension of the file dropped onto a windows form? For example (pseudocode below)

if extension = .xlsx { method1 }
if extension = .txt { method2 }
else { MessageBox.Show("Please drag/drop either a .xlsx or a .txt file"); }
Big Pimpin
  • 427
  • 9
  • 23
  • 2
    here you can find your answer with a simple google search [Get File Extension](https://msdn.microsoft.com/en-us/library/system.io.path.getextension%28v=vs.110%29.aspx) please show a little bit more effort – MethodMan Apr 06 '15 at 19:05
  • possible duplicate of [How do I drag and drop files into a C# application?](http://stackoverflow.com/questions/68598/how-do-i-drag-and-drop-files-into-a-c-sharp-application) – FreeAsInBeer Apr 06 '15 at 20:50

1 Answers1

3

You have to keep in mind that the user can drag more than a single file. Use this code as a starting point. First thing you want to do is modify the DragEnter event handler so the user simply can't drop the wrong kind of file at all:

    private void Form1_DragEnter(object sender, DragEventArgs e) {
        if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        foreach (var file in files) {
            var ext = System.IO.Path.GetExtension(file);
            if (ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase) ||
                ext.Equals(".txt",  StringComparison.CurrentCultureIgnoreCase)) {
                e.Effect = DragDropEffects.Copy;
                return;
            }
        }
    }

The DragDrop event handler is much the same, instead of assigning e.Effect you process the file, whatever you want to do with it.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536