1. Before this article begins
When uploading a file, an upload button is generally provided. Click Upload to pop up the file (or directory selection dialog box). After selecting the file (or directory), the file path is obtained from the dialog box object, and then uploaded.
dialog box to select file

The selection dialog box code is as follows:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "选择Exe文件";
openFileDialog.Filter = "exe文件|*.exe";
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "exe";
if (openFileDialog.ShowDialog() == false)
{
return;
}
string txtFile = openFileDialog.FileName;
But generally speaking, the best way for the user experience should be to directly drag and drop files with the mouse:
Baidu online disk drag-and-drop upload files

Here is a brief talk about the implementation of file drag-and-drop in WPF.
2. How to drag and drop files in WPF?
其实很简单,只要拖拽接受控件(或容器)注册这两个事件即可:DragEnter、Drop。
Let's first take a look at my implementation effect:
Drag and drop files into QuickApp

Registration events in Xaml
Registration event:
<Grid
MouseMove="Grid_MouseMove"
AllowDrop="True"
Drop="Grid_Drop"
DragEnter="Grid_DragEnter"
></Grid>
Event handling method:
- Grid_DragEnter processing method
private void Grid_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Link;
}
else
{
e.Effects = DragDropEffects.None;
}
}
DragDropEffects.Link: Handling drag-and-drop file operations
- Grid_Drop processing method
这是处理实际拖拽操作的方法,得到拖拽的文件路径(如果是操作系统文件快捷方式(扩展名为 lnk),则需要使用 com 组件(不是本文讲解重点,具体看本文开源项目)取得实际文件路径)后,即可处理后续操作(比如文件上传)。
private void Grid_Drop(object sender, DragEventArgs e)
{
try
{
var fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
MenuItemInfo menuItem = new MenuItemInfo() { FilePath = fileName };
// 快捷方式需要获取目标文件路径
if (fileName.ToLower().EndsWith("lnk"))
{
WshShell shell = new WshShell();
IWshShortcut wshShortcut = (IWshShortcut)shell.CreateShortcut(fileName);
menuItem.FilePath = wshShortcut.TargetPath;
}
ImageSource imageSource = SystemIcon.GetImageSource(true, menuItem.FilePath);
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
if (string.IsNullOrWhiteSpace(file.Extension))
{
menuItem.Name = file.Name;
}
else
{
menuItem.Name = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
}
menuItem.Type = MenuItemType.Exe;
if (ConfigHelper.AddNewMenuItem(menuItem))
{
AddNewMenuItem(menuItem);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
3. This article Over
The function is very simple, not deep, as long as you know how to use it.