Build a hierarchical treeview of files and directories dropped from a Windows Explorer window. Requires elevated trust running out of browser to avoid security exceptions when accessing the directory information in the FileInfo objects returned from the e.Data.GetData call.
<Grid x:Name="LayoutRoot" AllowDrop="True" Drop="LayoutRoot_Drop">
<my:TreeView x:Name="DirectoriesTreeView" Margin="50" Width="500" />
</Grid>
private void LayoutRoot_Drop(object sender, DragEventArgs e)
{
if (!Application.Current.HasElevatedPermissions e.Data == null)
return;
FileInfo[] fileInfos = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
if (fileInfos == null)
return;
List<FileInfo> sortedList = new List<FileInfo>(fileInfos);
sortedList.Sort((x, y) =>
{
if (x.Attributes == FileAttributes.Directory && y.Attributes != FileAttributes.Directory)
return -1;
if (y.Attributes == FileAttributes.Directory && x.Attributes != FileAttributes.Directory)
return 1;
return x.Name.CompareTo(y.Name);
});
foreach (FileInfo fileInfo in sortedList)
{
var newNode = new TreeViewItem { Header = fileInfo.Name };
DirectoriesTreeView.Items.Add(newNode);
if (!fileInfo.Exists)
ProcessDirectory(fileInfo, newNode);
}
}
private static void ProcessDirectory(FileSystemInfo fileSystemInfo, TreeViewItem currentNode)
{
DirectoryInfo directoryInfo = new DirectoryInfo(fileSystemInfo.FullName);
foreach (FileSystemInfo childFileSystemInfo in directoryInfo.EnumerateFileSystemInfos())
{
var newNode = new TreeViewItem { Header = childFileSystemInfo.Name };
currentNode.Items.Add(newNode);
if (childFileSystemInfo.Attributes == FileAttributes.Directory)
ProcessDirectory(childFileSystemInfo, newNode);
}
}