3

I am trying to copy an audio file to the clipboard in C# using a file path. The issue I am running into is that it is either not copying, or not copying correctly because it can not be pasted outside of the application.

Here is how I am trying to copy it to the clipboard:

b_array = File.ReadAllBytes(fileLocation);
Clipboard.Clear();
Clipboard.SetAudio(b_array);

the variable fileLocation in my testing equals something like: C:\Users\ben\Music\Samples\kick_05.wav

Benjamin Porter
  • 447
  • 2
  • 7
  • 18
  • Do you expect to be able to paste that file in windows explorer, for instance? With this code, you could only paste (I think, never tried audio) in an application that understands the audio format, so an audio editor of some sort. – Alex Paven May 08 '17 at 09:02
  • @AlexPaven I am trying to make it so you could paste the file just about anywhere (file explorer and audio editing programs) almost how the copy function works in the file explorer. – Benjamin Porter May 08 '17 at 21:26
  • 1
    I don't have a lot of experience with the clipboard but I think you need to insert a separate entry with the file info, otherwise there would be no way of knowing what the filename and location to copy from was - see Clipboard.SetFileDropList – Alex Paven May 09 '17 at 15:31

1 Answers1

5

No need to read the contents of the file. You can add the file directly to the clipboard using the SetFileDropList

StringCollection files = new StringCollection();
files.Add(fileLocation);
Clipboard.SetFileDropList(files);
Shawn Kendrot
  • 12,425
  • 1
  • 25
  • 41
  • I tried doing that and it threw an exception: System.Runtime.InteropServices.COMException: 'OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN))' – Benjamin Porter May 19 '17 at 16:11
  • Are you trying to do this in a background thread? I'm pretty sure it needs to happen on the UI thread. I've seen issues where using it inside a Task.Run would throw an exception – Shawn Kendrot May 19 '17 at 17:59
  • I am definitely doing this on the UI thread. I even wrapped it in this to make sure and I am having the same issue: this.Dispatcher.Invoke(() => { ... }); – Benjamin Porter May 20 '17 at 17:27
  • Which .NET version are you using? – Nemanja Banda May 22 '17 at 10:46
  • There's a known problem in version 4.0 that produces the error you are getting when using this approach, but it should be fixed in 4.5... This code works fine for me. You still might want to check [this](https://stackoverflow.com/a/13523188/780089) – Nemanja Banda May 23 '17 at 15:39
  • @NemanjaBanda I was trying to run this on Windows 10 using Parallels on my Mac. Transfer the project over to a PC and it works perfectly! – Benjamin Porter May 24 '17 at 01:12