Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET equivalent of Java FileChannel?

Tags:

c#

.net

tcp

nio

I want to stream bytes directly from a TCP socket to a file on disk. In Java, it's possible to use NIO Channels, specifically SocketChannel and FileChannel. Quoting FileChannel#transferFrom(...):

This method is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Obviously I can just write the standard "copy loop" to read and write the bytes, and even take advantage of asynchronous I/O to minimize waiting. Will that be comparable to the platform native functionality that Java is taking advantage of, or is there another approach?

like image 784
Ben Vitale Avatar asked Jul 13 '12 13:07

Ben Vitale


1 Answers

You can read the data with a NetworkStream, then use the CopyTo extension method to write the data into a FileStream.

A manual approach, pre .NET4: How do I save a stream to a file in C#?

For sending, there is a Socket.SendFile method that directly sends a file, utilizing the Win32 TransmitFile method. Unfortunately there is no corresponding Socket.ReceiveFile method or ReceiveFile Win32 API.

like image 199
Anders Abel Avatar answered Oct 21 '22 05:10

Anders Abel