I am sending a huge file over TCP using C#, and would like to measure the download speed.
How can I capture the transfer rate every second? If I use IPv4InterfaceStatistics or a similar method, I capture the device transfer rate instead of capturing the file transfer rate.
The problem with capturing device transfer rate is that it captures all data passing through the network device instead of the single file that I transfer.
How can I capture the file transfer rate?
Since you don’t have control over the stream to tell how much is read, you can create timestamps before and after a stream read and then calculate the speed based on the number of received or sent bytes:
You should put the
Stream.Readin atry/catchblock and handle exceptions that could occur. It’s the same for writing to streams and calculating the speed, only these two lines are affected: