.NET equivalent of Java FileChannel?

I want to transfer bytes directly from a TCP socket to a file on disk. In Java, you can use NIO channels, in particular SocketChannel and FileChannel . Quoting FileChannel#transferFrom(...) :

This method is potentially much more efficient than a simple loop that is read from the original channel and written to this channel. Many operating systems can transfer bytes directly from the source channel to the file system cache, without actually copying them.

Obviously, I can just write a standard β€œcopy loop” to read and write bytes, and even use asynchronous I / O to minimize the wait. Will this be comparable to the built-in functionality of the platform that Java uses, or is there a different approach?

+7
source share
1 answer

You can read the data using NetworkStream , then use CopyTo to write the data to FileStream.

Manual approach, pre.NET4: How to save a stream to a file in C #?

There is a Socket.SendFile method for sending, which directly sends the file using Win32 TransmitFile . Unfortunately, there is no corresponding Socket.ReceiveFile or ReceiveFile Win32 API method.

+3
source

All Articles