Tuesday, September 13, 2011

Pinging a Reader with C#

Here's a handy way to determine if a reader is connected to the network or not. It uses the .NET Ping and PingOptions classes, so make sure to add the following namespace to your project.
using System.Net.NetworkInformation;

Then, you can write a method like this, that returns true if the reader is connected and false if it is not.
private bool ReaderIsAvailable(string address){    Ping pingSender = new Ping();    PingOptions options = new PingOptions();    options.DontFragment = true;    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";    byte[] buffer = Encoding.ASCII.GetBytes(data);    int timeout = 120;    PingReply reply = pingSender.Send(address, timeout, buffer, options);    if (reply.Status == IPStatus.Success)        return true;    else        return false;}

Finally, this is how you would call the method
if (ReaderIsAvailable("SpeedwayR-10-25-32")){    // Reader is connected to the network.    // Start reading some tags!}else{    // Reader is not connected to the network.    // Handle it here.}