I had to do the same thing, no new info but this snippet may come in handy for the next person looking for a way to do this in C#.
note that this method only counts the number of consecutive 1s, and leaves you the work of appending it to the IP.
public class IPAddressHelper
{
public static UInt32 SubnetToCIDR(string subnetStr)
{
IPAddress subnetAddress = IPAddress.Parse(subnetStr);
byte[] ipParts = subnetAddress.GetAddressBytes();
UInt32 subnet = 16777216 * Convert.ToUInt32(ipParts[0]) + 65536 * Convert.ToUInt32(ipParts[1]) + 256 * Convert.ToUInt32(ipParts[2]) + Convert.ToUInt32(ipParts[3]);
UInt32 mask = 0x80000000;
UInt32 subnetConsecutiveOnes = 0;
for (int i = 0; i < 32; i++)
{
if (!(mask & subnet).Equals(mask)) break;
subnetConsecutiveOnes++;
mask = mask >> 1;
}
return subnetConsecutiveOnes;
}
}