Aussie Ausbourne
Aussie Ausbourne

Reputation: 211

How to Create a Download speed test with .NET

I'd like to create a speed test to test the connection.

What I would like is a 15sec download which then gives me the average download speed.

Anyone knows how to create this? or has a better idea to make a speed test?

Upvotes: 21

Views: 46375

Answers (7)

kay.one
kay.one

Reputation: 7692

This sample will try to download googletalk, and then outputs details of the download.

ps. when trying to time and operation avoid using DateTime as they can cause problems or inacurecy, always use Stopwatch available at System.Diagnostics namespace.

const string tempfile = "tempfile.tmp";
System.Net.WebClient webClient = new System.Net.WebClient();

Console.WriteLine("Downloading file....");

System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
webClient.DownloadFile("http://dl.google.com/googletalk/googletalk-setup.exe", tempfile);
sw.Stop();

System.IO.FileInfo fileInfo = new System.IO.FileInfo(tempfile);
long speed = fileInfo.Length / sw.Elapsed.Seconds;

Console.WriteLine("Download duration: {0}", sw.Elapsed);
Console.WriteLine("File size: {0}", fileInfo.Length.ToString("N0"));
Console.WriteLine("Speed: {0} bps ", speed.ToString("N0"));

Console.WriteLine("Press any key to continue...");
Console.ReadLine();

Upvotes: 16

Dane Balia
Dane Balia

Reputation: 5367

Publication: Understanding broadband speed measurements

This may help someone looking to implement a speed test with the supporting theory. The general algorithm can be seen here:

Ookla Algorithm

Upvotes: 1

T-moty
T-moty

Reputation: 2797

As publicENEMY says, the kay.one's answer could give a wrong speed, because the HDD's speed can be lower than the network speed (for example: Google Gigabit Fiber is much faster than a 5200rpm HDD's average write speed)

This is an example code derived from the kay.one's answer, but downloads the data content into a System.Byte[], and therefore in memory.

Also i notice that after the very first download, the speed increases dramatically and jumps over the real network speed, because System.Net.WebClient uses the IE's download cache: for my requirements i only add the t querystring parameter, clearly unique for each request.

EDIT

as.beaulieu finds an issue using TimeSpan.Seconds for the calculation, both for very fast and very slow downloads.

We just need to use TimeSpan.TotalSeconds instead.

Console.WriteLine("Downloading file....");

var watch = new Stopwatch();

byte[] data;
using (var client = new System.Net.WebClient())
{
    watch.Start();
    data = client.DownloadData("http://dl.google.com/googletalk/googletalk-setup.exe?t=" + DateTime.Now.Ticks);
    watch.Stop();
}

var speed = data.LongLength / watch.Elapsed.TotalSeconds; // instead of [Seconds] property

Console.WriteLine("Download duration: {0}", watch.Elapsed);
Console.WriteLine("File size: {0}", data.Length.ToString("N0"));
Console.WriteLine("Speed: {0} bps ", speed.ToString("N0"));

Console.WriteLine("Press any key to continue...");
Console.ReadLine();

Upvotes: 17

user3106790
user3106790

Reputation:

Use the code to check internet connection speed using C#:

private long bytesReceivedPrev = 0;
    private void CheckBandwidthUsage(DateTime now)
    {
        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        long bytesReceived = 0;
        foreach (NetworkInterface inf in interfaces)
        {
            if (inf.OperationalStatus == OperationalStatus.Up &&
                inf.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                inf.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
                inf.NetworkInterfaceType != NetworkInterfaceType.Unknown && !inf.IsReceiveOnly)
            {
                bytesReceived += inf.GetIPv4Statistics().BytesReceived;
            }
        }

        if (bytesReceivedPrev == 0)
        {
            bytesReceivedPrev = bytesReceived;
        }
        long bytesUsed = bytesReceived - bytesReceivedPrev;
        double kBytesUsed = bytesUsed / 1024;
        double mBytesUsed = kBytesUsed / 1024;
        internetUsage.Add(now, mBytesUsed);
        if (internetUsage.Count > 20)
        {
            internetUsage.Remove(internetUsage.Keys.First());
        }
        bytesReceivedPrev = bytesReceived;
    }

    private void CheckInternetSpeed(DateTime now)
    {
        WebClient client = new WebClient();
        Uri URL = new Uri("http://sixhoej.net/speedtest/1024kb.txt");
        double starttime = Environment.TickCount;
        client.DownloadFile(URL, Constants.GetAppDataPath() + "\\" + now.Ticks);
        double endtime = Environment.TickCount;

        double secs = Math.Floor(endtime - starttime) / 1000;

        double secs2 = Math.Round(secs, 0);

        double kbsec = Math.Round(1024 / secs);

        double mbsec = kbsec / 100;

        internetSpeed.Add(now, mbsec);
        if (internetSpeed.Count > 20)
        {
            internetSpeed.Remove(internetSpeed.Keys.First());
        }
        client.Dispose();
        try
        {
            // delete downloaded file
            System.IO.File.Delete(Constants.GetAppDataPath() + "\\" + now.Ticks);
        }
        catch (Exception ex1)
        {
            Console.WriteLine(ex1.Message);
        }
    }

Upvotes: 0

Vineet Menon
Vineet Menon

Reputation: 738

how can a download file give you correct link speed. what you get by downloading file is a great underestimate of the actual speed what you get.

What i think is you should do some udp sort of packet transfer and find the time required to receive it at the other end.

regards,

Upvotes: 2

Omar Abid
Omar Abid

Reputation: 15976

In Visual Basic dot net, the "My" class provide a function to download files, try to search for its alias in C#. Then create a timer counter and count seconds ellapsed since the download began.

Upvotes: 0

Matt Campbell
Matt Campbell

Reputation: 253

  • Use a known file size and trap how long it takes to download. (using two DateTime.now()s)

There is a library on CodeProject that I found. It is a couple of C# classes that let you monitor your network connections including upload and download speeds. Link here

Upvotes: 4

Related Questions