一、本文開始之前
上傳文件時,一般是提供一個上傳按鈕,點擊上傳,彈出文件(或者目錄選擇對話框),選擇文件(或者目錄)後,從對話框對象中取得文件路徑後,再進行上傳操作。
對話框選擇文件

選擇對話框代碼如下:
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;
但一般來說,對用戶體驗最好的,應該是直接滑鼠拖拽文件了:
百度網盤拖拽上傳文件

下面簡單說說 wpf 中文件拖拽的實現方式。
二、wpf 中怎樣拖拽文件呢?
其实很简单,只要拖拽接受控件(或容器)注册这两个事件即可:DragEnter、Drop。
先看看我的實現效果:
拖拽文件進 quickapp 中

xaml 中註冊事件
註冊事件:
<Grid
MouseMove="Grid_MouseMove"
AllowDrop="True"
Drop="Grid_Drop"
DragEnter="Grid_DragEnter"
></Grid>
事件處理方法:
- grid_dragenter 處理方法
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:處理拖拽文件操作
- grid_drop 處理方法
这是处理实际拖拽操作的方法,得到拖拽的文件路径(如果是操作系统文件快捷方式(扩展名为 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);
}
}
三、本文 over
功能很簡單,不求精深,會用就行。