WPF拖拽文件(拖入拖出),监控拖拽到哪个位置,类似百度网盘拖拽

1.往wpf中拖文件

// xaml
<Grid x:Name="grid_11" DragOver="Grid_11_DragOver" Drop="Grid_11_Drop" AllowDrop="True" Background="Red"/>
// xaml.cs
/// <summary>
/// 包含目录文件判断
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
private bool HasDirectory(string[] files)
{
    if (files == null)
        return false;
    for (int i = 0; i < files.Length; i++)
    {
        if (System.IO.Directory.Exists(files[i]))
        {
            return true;
        }
    }
    return false;
}
/// <summary>
/// 抛弃文件夹目标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Grid_11_DragOver(object sender, DragEventArgs e)
{
    var files = (string[])e.Data.GetData(DataFormats.FileDrop);
    if (HasDirectory(files))
    {
        e.Effects = DragDropEffects.None;// 抛弃这一次的拖拽源
        e.Handled = true;
    }
}
/// <summary>
/// 放下文件获取路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Grid_11_Drop(object sender, DragEventArgs e)
{
    var files = (string[])e.Data.GetData(DataFormats.FileDrop);
    if (files == null || HasDirectory(files))
        return;
    for(int i = 0; i < files.Length; i++)
    {
        Console.WriteLine(files[i]);
    }
}

2.wpf中往外拖文件

private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)// 右键拖拽的时候,创建一个drop源
{
    // 多文件拖拽
    #region 获取拖拽的文件的个数
    int fileCount = 1;
    #endregion

    FileDDWatcher.Instance.StartWatcher(fileCount);// 启动文件挪移监控,传入文件挪移的个数

    #region 创建临时文件并反馈临时路径,paths挪移的目标

    string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "TempDirectory");
    if (!System.IO.Directory.Exists(dir))
    {
        System.IO.Directory.CreateDirectory(dir);
    }
    string[] paths = new string[fileCount];
    for (int i = 0; i < fileCount; i++)
    {
        string path = System.IO.Path.Combine(dir, $"fileName{i}.download");
        System.IO.File.Create(path).Close();// 拖动的时候创建
        paths[i] = path;
    }
    #endregion

    #region 拖拽代码

    ListView lv = new ListView();
    string dataFormat = DataFormats.FileDrop;
    DataObject dataObject = new DataObject(dataFormat, paths);//(listview.SelectedItems.Cast<string>()).ToArray<string>());
    DragDropEffects dde = DragDrop.DoDragDrop(lv, dataObject, DragDropEffects.Copy);

    #endregion

    FileDDWatcher.Instance.StopWatcher();// 停止文件监控

    #region 拖拽成功之后获取目标的路径
    Console.WriteLine($"dropdrag status = {dde}");
    if (dde == DragDropEffects.Copy)// 拖拽成功
    {
        string[] ls = FileDDWatcher.Instance.GetTempFilePath();// 获取拖拽之后的目录
        if (ls != null && ls.Length > 0)
        {
            for (int i = 0; i < ls.Length; i++)
            {
                Console.WriteLine($"Target catalogue {ls[i]}");
            }
        }
        else
        {
            Console.WriteLine("no file path copy");
        }
    }
    #endregion
}

 

监控文件的代码

public class FileDDWatcher
{
    #region property && fileds

    private Hashtable tempWatchers = null;
    private Queue<string> pathQueue = new Queue<string>();
    private int moveFileCount = 0;

    #endregion

    #region instance
    private static object ooo = new object();
    private static FileDDWatcher _instance;
    public static FileDDWatcher Instance
    {
        get
        {
            lock (ooo)
            {
                if (_instance == null)
                {
                    _instance = new FileDDWatcher();
                }
                return _instance;
            }
        }
    }
    private FileDDWatcher() { }
    #endregion

    #region method

    #region private

    /// <summary>
    /// 文件监控触发的事件
    /// </summary>
    /// <returns></returns>       
    private void OnCreated(object source, FileSystemEventArgs e)
    {
        string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "TempDirectory");
        if (e.FullPath.Contains(path))
        {
            return;
        }
        pathQueue.Enqueue(e.FullPath);
    }

    #endregion

    #region public

    /// <summary>
    /// 启动文件监控,传入移动文件的个数,默认是1个
    /// </summary>
    /// <returns></returns>
    public bool StartWatcher(int fileCount = 1)
    {
        LogHelper.WriteInfo("StartWatcher");
        try
        {
            moveFileCount = fileCount;
            int i = 1;
            if (tempWatchers == null || tempWatchers.Count <= 0)
            {
                tempWatchers = new Hashtable();
                foreach (string driveName in Directory.GetLogicalDrives())
                {
                    if (Directory.Exists(driveName))
                    {
                        FileSystemWatcher watcher = new FileSystemWatcher();
                        watcher.Filter = "*.download";
                        watcher.NotifyFilter = NotifyFilters.FileName;
                        watcher.Created -= OnCreated;
                        watcher.Created += OnCreated;
                        watcher.IncludeSubdirectories = true;// 必须要的,监控子集目录
                        watcher.Path = driveName;
                        LogHelper.WriteInfo(driveName);
                        watcher.EnableRaisingEvents = true;
                        tempWatchers.Add("file_watcher" + i.ToString(), watcher);
                        i++;
                    }
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            LogHelper.WriteError(ex.Message);
            return false;
        }
    }
    /// <summary>
    /// 停止文件监控,如果队列中路径数量和文件移动数量一致,就不重置文件传输个数
    /// </summary>
    /// <returns></returns>
    public bool StopWatcher()
    {
        try
        {if (tempWatchers != null && tempWatchers.Count > 0)
            {
                LogHelper.WriteInfo(tempWatchers.Count + "");
                for (int i = 1; i <= tempWatchers.Count; i++)
                {
                    ((FileSystemWatcher)tempWatchers["file_watcher" + i.ToString()]).Dispose();
                }
                tempWatchers.Clear();
                tempWatchers = null;
            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
        finally
        {
            moveFileCount = 0;
        }
    }
    /// <summary>
    /// 返回文件保存的路径
    /// </summary>
    /// <returns></returns>
    public string[] GetTempFilePath()
    {
        try
        {
            int length = pathQueue.Count;
            if (length <= 0)
            {
                return new string[0];
            }

            string[] ls = new string[length];
            for (int i = 0; i < length; i++)
            {
                ls[i] = pathQueue.Dequeue();
            }
            return ls;
        }
        catch (Exception ex)
        {
            return new string[0];
        }
        finally
        {
            moveFileCount = 0;
        }
    }
    #endregion

    #endregion
}

 

posted @ 2019-07-26 13:55  xiao贝  阅读(648)  评论(0编辑  收藏