翻过高山走不出你
为什么要有一个文本文件?这是我解决问题的方法,使用 DataTable 存储数据并收集数据: //Create the process using (Process ns = new Process()) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("Protocol"), new DataColumn("Local Address"), new DataColumn("Foreign Address"), new DataColumn("State"), new DataColumn("PID"), new DataColumn("Process Name"), }); ProcessStartInfo psi = new ProcessStartInfo("netstat.exe", "-ano"); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; ns.StartInfo = psi; // Run it, and read the results ns.Start(); using (StreamReader r = ns.StandardOutput) { string output = r.ReadToEnd(); ns.WaitForExit(); //Parse those results into a DataTable, polling the Process info string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (string line in lines) { string[] elements = line.Split(' '); if (elements.Length < 5) continue; if (elements.Contains("Proto")) continue; DataRow dr = dt.NewRow(); List<string> validElements = new List<string>(); //Weed out empty elements. foreach (string element in elements) { //skip blanks if (element.Trim() == "") continue; validElements.Add(element); } foreach (string element in validElements) { foreach (DataColumn dc in dt.Columns) { // fill in the buckets. Note that UDP doesn't have a state if (dr["Protocol"].ToString() == "UDP" && dc.ColumnName == "State") continue; if (dr[dc] == DBNull.Value) { dr[dc] = element; break; } } } dr["Process Name"] = Process.GetProcessById(int.Parse(dr["PID"].ToString())).ProcessName; dt.Rows.Add(dr); } } }这是我的结果数据的简短屏幕截图:然后我可以用这些数据在代码中做任何我想做的事情。至少我会这么做。