I am working on a WPF application which shows a list of files stored on a remote server (just like dropbox). I want users to drag and drop them onto desktop or any folder. There are many questions posted related to this but none of them really give a complete solution.
Here is the complete code I am using https://github.com/dotriz/VirtualDragDrop/
This is a very simple task if file is stored on local system, but here file is on a remote server and need to be downloaded first.
The only article related to this, is 13 years old posted here https://dlaa.me/blog/post/9923072. It has few issues too, like
- When we drag it on Windows explorer it gives error in DEBUG mode but works fine when we run exe directly. What could be issue?
Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC)
- If we drag the file to an application like Slack, it hangs while file is downloading. But works fine (if we run exe directly) when file is dropped on to Windows Explorer.
Here is the code used on MouseDown event of a label. It uses VirtualFileDataObject class from the link given above
private void VirtualFile2_MouseButtonDown(object sender, MouseButtonEventArgs e)
{
var virtualFileDataObject = new VirtualFileDataObject();
virtualFileDataObject.SetData(new VirtualFileDataObject.FileDescriptor[]
{
new VirtualFileDataObject.FileDescriptor
{
Name = "test.zip",
ChangeTimeUtc = DateTime.Now.AddDays(-1),
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://somesite.com/test.zip");
stream.Write(data, 0, data.Length);
}
}
},
});
DoDragDropOrClipboardSetDataObject(e.ChangedButton, VirtualFile2, virtualFileDataObject, DragDropEffects.Copy);
}
private static void DoDragDropOrClipboardSetDataObject(MouseButton button, DependencyObject dragSource, VirtualFileDataObject virtualFileDataObject, DragDropEffects allowedEffects)
{
try
{
VirtualFileDataObject.DoDragDrop(dragSource, virtualFileDataObject, allowedEffects);
}
catch (COMException)
{
// Failure; no way to recover
}
}