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

選擇對話方塊程式碼如下:
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
功能很簡單,不求精深,會用就行。