I would like to express my thanks for the code implementation of the following functions on the Internet.
Of course, based on the Operation ideas in this example, you can implement more useful functions that you want to root.
------------------------------
// TextBox1 is used to enter the port to be queried
// TextBox2 is used to display original netstat-an information
// TextBox3 is used to display the port information of the local machine.
// TextBox4 is used to show whether the port is occupied
Protected void button#click (object sender, EventArgs e)
{
This. TextBox2.Text = "";
Process p = new Process ();
P. StartInfo. FileName = "cmd.exe ";
P. StartInfo. UseShellExecute = false;
P. StartInfo. RedirectStandardInput = true;
P. StartInfo. RedirectStandardOutput = true;
P. StartInfo. RedirectStandardError = true;
P. StartInfo. CreateNoWindow = true;
P. Start ();
// View the port usage on the local machine
P. StandardInput. WriteLine ("netstat-");
P. StandardInput. WriteLine ("exit ");
//
StreamReader reader = p. StandardOutput; // captures the output stream
String strAllInfo = "";
String strLocalInfo = "";
String strLine = reader. ReadLine (); // read a row each time
Int I = 0;
While (! Reader. EndOfStream)
{
StrAllInfo + = strLine + "\ r \ n ";
I ++;
If (I <9) // remove the previous information
{
/*
Microsoft Windows [version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.
E: \ Documents ents and Settings \ Administrator> netstat-
Active Connections
Proto Local Address Foreign Address State
*/
}
Else
{
If (strLine. Trim (). Length> 0)
{
StrLine = strLine. Trim ();
Regex r = new Regex (@ "\ s + ");
String [] strArr = r. Split (strLine );
StrLocalInfo + = strArr [1] + "| \ r \ n ";
}
}
StrLine = reader. ReadLine (); // next row
}
P. WaitForExit (); // wait for the program to exit after execution
P. Close (); // Close the process
Reader. Close (); // Close the stream
This. TextBox2.Text = strAllInfo; // displays the original information of netstat-.
This. TextBox3.Text = strLocalInfo; // display the local port information
// Compare the port
If (strLocalInfo. IndexOf (":" + this. TextBox1.Text + "|")> = 0)
{
This. TextBox4.Text = "occupied ";
}
Else
{
This. TextBox4.Text = "available ";
}
}