我在文件(目录或任何类型的文件)上使用拖放列表视图。 当我从桌面拖放My Computer或Bin时,会发生NullReferenceException。
我只想跳过此元素(在日志文本框中或显示内容中显示一些文本)。 我不知道如何实现这一目标。我不知道Desktop中的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 ");
}
}
答案 0 :(得分:0)
感谢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");
}
}
}