啟動 netstat -na 進程,導向標準輸出,解析文字行。
public string GetPortList() {
ProcessStartInfo info = new ProcessStartInfo {
FileName = "netstat", Arguments = "-na",
CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true
};
Process p = Process.Start(info);
p.WaitForExit();
StringBuilder sb = new StringBuilder();
int row = 0;
using (StreamReader reader = p.StandardOutput) {
while (!reader.EndOfStream) {
string line = reader.ReadLine().Trim();
if (row++ > 3) sb.AppendLine(line); // 跳過標題行
}
}
return sb.ToString();
}
封裝於 PortHelper 類別,供應用程式呼叫取得完整連接埠清單。