you don't have to write code to check whether a port is open or not. you can use telnet application:
telnet localhost 21
But if you need to check it in code, you can use TcpClient:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Test_TcpConnect
{
class Program
{
static void Main(string[] args)
{
try
{
using (TcpClient cl = new TcpClient("localhost", 21))
{
Console.WriteLine("connected");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}