Drag and drop exception. Desktop objects [duplicate]

我与影子孤独终老i 提交于 2019-12-11 17:47:16

问题


I am using Drag & Drop ListView on files (directories or any kind of files). When i drag&drop My Computer or Bin from Desktop NullReferenceException happens.

All i want is to skip this element (display some text in log textbox or smthing). I have no idea how to achieve that. I don't know what kind of object is MyComputer element from Desktop.

Here's my code after cutting useless to this subject logic:

private void Directories_ListView_DragDrop(object sender, DragEventArgs e)
    {

        string[] DroppedDirectories = (string[]) e.Data.GetData(DataFormats.FileDrop,false); //array of dd files paths
        try
        {
            foreach (var directory in DroppedDirectories) // here Exception  occurs this loop process all dragged and drop files 
            {
                ListViewItem Dir = new ListViewItem(Path.GetFileNameWithoutExtension(directory));
                //Place for some checking Logic
                if (GetDir.IsDirectory(directory))
                {
                   (.....);// Doing some things
                }
                else
                    LogList.Items.Add(DateTime.Now + ": Entry " + Dir.Text + " is not a directory");

            }
        }
        catch(Exception) // it only stops app from crashing, 
        {
            LogList.Items.Add(DateTime.Now + "One of elements was Mycomputer or Bin, process stopped ");
        }
    }

回答1:


Thanks to LarsTech and Abion47 your solution is to wrap your drag drop code in this condition:

if (e.Data.GetData(DataFormats.FileDrop, false) != null)
{
    string[] DroppedDirectories = (string[]) e.Data.GetData(DataFormats.FileDrop,false);

    foreach(string directory in DroppedDirectories)
    {
        try
        {
            ListViewItem Dir = new ListViewItem(Path.GetFileNameWithoutExtension(directory));
            //Rest of code
        }
        catch(Exception ex)
        {
            LogList.Items.Add(DateTime.Now + ": Entry " + directory + " is not a directory");
        }
    }
}


来源:https://stackoverflow.com/questions/51641659/drag-and-drop-exception-desktop-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!