Home > Mobile >  File access System.IO.Exception after CopyEnhMetaFile() even though DeleteEnhMetaFile() is called
File access System.IO.Exception after CopyEnhMetaFile() even though DeleteEnhMetaFile() is called

Time:05-09

I am using the below code to get an IntPtr to an EMF file on the clipboard. The file is created without error, but when I try to delete the file in Windows Explorer while my application is still running, I get this exception:

System.IO.IOException: 'The process cannot access the file 'xyz.emf' because it is being used by another process.'

I also tried using New MetaFile(ptr, False) and manually calling DeleteEnhMetaFile(), but the error stays the same.

 Dim ptr As IntPtr = NativeMethods.GetClipboardData(14)
 If Not ptr.Equals(IntPtr.Zero) Then

     Using mf As New Metafile(ptr, True)

         NativeMethods.CopyEnhMetaFile(ptr, $"{somePath}\{fileName}.emf")
         'NativeMethods.DeleteEnhMetaFile(ptr)

     End Using
 End If

How should I clean up the IntPtr to the EMF file so that I can delete the file after the above code has run?

EDIT: I even cannot delete the file from within my application while it is still running.

CodePudding user response:

You need to call DeleteEnhMetaFile() (or assign ownership to a Metafile) on the copied handle returned by CopyEnhMetaFile(), not on the handle returned by GetClipboardData(). The clipboard owns the original handle.

Dim ptr As IntPtr = NativeMethods.GetClipboardData(14)
If Not ptr.Equals(IntPtr.Zero) Then

    Dim ptrCopy as IntPtr = NativeMethods.CopyEnhMetaFile(ptr, $"{somePath}\{fileName}.emf")
    ...
    NativeMethods.DeleteEnhMetaFile(ptrCopy)

End If
  • Related