C# 拖放异常。桌面对象

C# 拖放异常。桌面对象,c#,winforms,exception,drag-and-drop,C#,Winforms,Exception,Drag And Drop,我在文件(目录或任何类型的文件)上使用拖放列表视图。 当我从桌面拖放计算机或垃圾箱时,会发生NullReferenceException 我只想跳过这个元素(在日志文本框或smthing中显示一些文本)。 我不知道如何做到这一点。我不知道桌面上的MyComputer元素是什么类型的对象 以下是我的代码,在对这个主题的逻辑进行裁剪之后: private void Directories_ListView_DragDrop(object sender, DragEventArgs e) {

我在文件(目录或任何类型的文件)上使用拖放列表视图。 当我从桌面拖放计算机或垃圾箱时,会发生NullReferenceException

我只想跳过这个元素(在日志文本框或smthing中显示一些文本)。 我不知道如何做到这一点。我不知道桌面上的MyComputer元素是什么类型的对象

以下是我的代码,在对这个主题的逻辑进行裁剪之后:

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 ");
        }
    }

感谢LarsTech和Abion47,您的解决方案是在这种情况下包装拖放代码:

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");
        }
    }
}

WinForms?WPF?UWP?还有别的吗?“桌面”标签很模糊。更正了。你的链接与主题没有任何关系。你的listview是如何配置的?我正在尝试实现您的代码,但我发现AllowDrop=true的事件正在处理DragDrop。当我从桌面拖动回收站时,它会显示“不允许”符号,并且不会将其删除。@您需要DragEnter事件。@TamaraL96您说您得到的是NullReferenceException。链接的问题包含一个全面的演练,介绍如何调试这些类型的异常,因此是重复的。感谢大家的帮助:)@Abion47感谢您执行解决方案过程。代码工作正常,但如果您拖放几个文件,其中一个是Bin或Mycomputer,其他文件仍未处理。我将在tommorow尝试解决这个问题。在处理它之前,您需要检查每个“目录”——或者只是将foreach循环的内容包装在一个try-catch中,这样您只会捕获失败的项,然后可以处理下一个。我已经更新了答案。我将测试您的改进代码:)我的概念是去掉foreach循环,并用for循环(I)替换它