Get File Extension of File Dropped Onto Windows Form [closed]

大憨熊 提交于 2019-12-08 07:35:38

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/29477498/get-file-extension-of-file-dropped-onto-windows-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!