9

In Java I'd use the java.nio library and use FileChannel.transferTo() and FileChannel.transferFrom(). Is there something similar in (specifically) C# or am I going to have to load some unamanaged .dll from somewhere? Google has not been useful in this case.

Edit: I should note that I'm targeting .NET 3.5.

ldam
  • 4,412
  • 6
  • 45
  • 76
  • 2
    I think you're looking for the [TransmitFile API](http://msdn.microsoft.com/en-us/library/windows/desktop/ms740565.aspx), and it looks like you have to PInvoke it. I'm pretty sure the managed Stream classes do not perform zero-copying. – John Rasch Mar 21 '13 at 17:13
  • @JohnRasch that looks like it... I also figured the managed classes wouldn't actually do zero-copy. – ldam Mar 21 '13 at 17:15
  • And right at the bottom someone has said it doesn't like files > 2GB: `For files > 2GB, it fails with ERROR_INVALID_PARAMETER` – ldam Mar 21 '13 at 17:16

1 Answers1

2

I think the best performing equivalent might be UnmanagedMemoryStream.

This class supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.

Although I've never had cause to do this, so can't vouch for appropriateness of this class (or of using unmanaged code/memory in your scenario).

Sepster
  • 4,800
  • 20
  • 38
  • @LoganDam What did you do in the end? (You can post/accept your own solution). I can only assume my downvoter was doing so based on your statement _"...or am I going to have to load some unmanaged .dll from somewhere"_. In case it wasn't clear from the link, this is a .NET Framework class, available out-of-the box to any eg class lib or console app via `mscorlib.dll`. – Sepster Mar 25 '13 at 12:42
  • I haven't done anything yet. This was a research question :) when (if) I eventually get around to implementation I'll be sure to come back and update this question. – ldam Apr 20 '13 at 15:41
  • @LoganDam Cool. I'll be interested to see how you tackle this, so have added question as a favourite. Good luck with it ;-) – Sepster Apr 20 '13 at 16:11
  • 1
    Actually doing more research now, it looks like the only way to do this is through the `TransmitFile` API that @JohnRasch suggested, but everywhere I look for this supposed 2GB limit indicates it's a bug in Windows XP. I will have to test on later versions. My idea was actually intended for Windows Phone, but it looks like that's out of the question now since Windows Phone doesn't support this native call by the looks of things. :( – ldam Apr 20 '13 at 16:52
  • From the documentation, I also believe `UnmanagedMemoryStream` does, in fact, involve CPU and memory access, unlike background DMA. – mafu Mar 28 '20 at 15:17