文件丢失到Windows窗体的文件扩展名 [英] Get File Extension of File Dropped Onto Windows Form
本文介绍了文件丢失到Windows窗体的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何捕获丢失到Windows窗体上的文件的文件扩展名?例如(下面的伪代码)
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"); }
推荐答案
你必须记住,用户可以比单个文件拖动更多。使用此代码作为起点。首先要做的是修改DragEnter事件处理程序,以便用户根本无法丢弃错误的文件类型:
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;
}
}
}
DragDrop事件处理程序很多同样的,而不是分配e.Effect你处理文件,无论你想要做什么。
The DragDrop event handler is much the same, instead of assigning e.Effect you process the file, whatever you want to do with it.
这篇关于文件丢失到Windows窗体的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文