I need to retrieve paths of files and folders currently copied into the clipboard, is this possible in C#?
So let's say I do Ctrl C a folder. That folder will go to clipboard, I need a way to extract the path to that folder. Same goes for copied files.
I'm developing a file server, I already can send files and folders: all I need is to provide a list of paths to the function.
CodePudding user response:
Microsoft supplies some samples about it:
Have a look at: DragDropOpenTextFile
This is the method used to check it there is a file copied in the clipboard:
// If the data object in args is a single file, this method will return the filename.
// Otherwise, it returns null.
private string IsSingleFile(DragEventArgs args)
{
// Check for files in the hovering data object.
if (args.Data.GetDataPresent(DataFormats.FileDrop, true))
{
var fileNames = args.Data.GetData(DataFormats.FileDrop, true) as string[];
// Check for a single file or folder.
if (fileNames?.Length is 1)
{
// Check for a file (a directory will return false).
if (File.Exists(fileNames[0]))
{
// At this point we know there is a single file.
return fileNames[0];
}
}
}
return null;
}
You get a DragEventArgs from the Drop event handler of your control.
private void EhDrop(object sender, DragEventArgs args)
{
// Mark the event as handled, so Control's native Drop handler is not called.
args.Handled = true;
var fileName = IsSingleFile(args);
if (fileName != null)
{
// Do something.
}
}
CodePudding user response:
Ok got it to work myself, Clipboard.GetFileDropList()
gets you both files and folders paths, what a neat little function!
var unparsedFilesList = Clipboard.GetFileDropList();
foreach(var filePath in unparsedFilesList)
{
MessageBox.Show(filePath);
}