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"); }
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"); }
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.