以逗号's分隔的字符串行打印所有4个ping

本文关键字:打印 字符串 ping 4个 分隔 | 更新日期: 2023-09-27 18:18:27

我的代码工作得很好,但是它将结果保存到.csv文件的地方,我需要在那里做一些更改。我的结果是:

www.yahoo.com , 98.139.183.24 , 137
www.att.com , 23.72.249.145 , 20
www.yahoo.com , 98.139.183.24 , 120
www.att.com , 23.72.249.145 , 16

,我希望我的结果是:

www.yahoo.com , 137 , 120
www.att.com , 20 , 16

在这个例子中,我只共享了两个结果,我实际上返回了4个结果,我需要把它们都放在一行中,我还需要摆脱IP地址。请帮帮我。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lstWebSites = new List<string>();
            lstWebSites.Add("www.yahoo.com");
            lstWebSites.Add("www.att.com");
            lstWebSites.Add("www.verizon.com");
            string filename = @"PingLog.csv";
            {
                using (var writer = new StreamWriter(filename, true)) 
                {
                    for (int i = 0; i < 4; i++)
                    foreach(string website in lstWebSites)
                    {
                        //writer.WriteLine(website, lstWebSites);
                        try
                        {
                            Ping myPing = new Ping();
                            PingReply reply = myPing.Send(website, 1000);
                            if (reply != null)
                            {
                                writer.WriteLine(website + " , " + reply.Address.ToString() + " , " + reply.RoundtripTime);
                            }
                        }                   
                        catch
                        {
                            Console.WriteLine("ERROR: You have some TIMEOUT issue");
                        }
                    }
                }
            }
        }
    }
}

以逗号's分隔的字符串行打印所有4个ping

如果您想显示Ping调用的所有结果,那么您可以使用Dictionary<string, List<PingReply>>,而不是简单地使用List<string>来保存站点的名称。通过这种方式,对于每个指向某个站点的ping,您保留收到的所有PingReply的列表,并在循环结束时将所有内容写入文件中(在Linq的一点点帮助下)

static void Main(string[] args)
{
    // Dictionary to keep the sites list and the list of replies for each site
    Dictionary<string, List<PingReply>> lstWebSites = new Dictionary<string, List<PingReply>>();
    lstWebSites.Add("www.yahoo.com", new List<PingReply>());
    lstWebSites.Add("www.att.com", new List<PingReply>());
    lstWebSites.Add("www.verizon.com", new List<PingReply>());
    string filename = @"d:'temp'PingLog.csv";
    // Start your loops
    for (int i = 0; i < 4; i++)
        foreach (string website in lstWebSites.Keys)
        {
            try
            {
                Ping myPing = new Ping();
                PingReply reply = myPing.Send(website, 1000);
                if (reply != null)
                {
                    // Do not write to file here, just add the 
                    // the reply to your dictionary using the site key
                    lstWebSites[website].Add(reply);
                }
            }
            catch
            {
                Console.WriteLine("ERROR: You have some TIMEOUT issue");
            }
        }

    using (var writer = new StreamWriter(filename, false))
    {
        // For each site, extract the RoundtripTime and 
        // use string.Join to create a comma separated line to write
        foreach(string website in lstWebSites.Keys)
            writer.WriteLine(website + " , " + 
                string.Join(",", lstWebSites[website]
                      .Select(x => x.RoundtripTime)
                      .ToArray()));
    }
    string fileText = File.ReadAllText(filename);
    Console.WriteLine(fileText);
}

最简单的方法是将for循环移动到foreach循环中,并收集每个站点的ping结果。您可以将代码更改为以下内容:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var lstWebSites = new List<string>
            {
                "www.yahoo.com",
                "www.att.com",
                "www.verizon.com"
            };
            var filename = @"PingLog.csv";
            {
                using (var writer = new StreamWriter(filename, true))
                {
                    foreach (var website in lstWebSites)
                    {
                        var roundTripTimes = new List<long>();
                        for (var i = 0; i < 4; i++)
                        {
                            try
                            {
                                var myPing = new Ping();
                                var reply = myPing.Send(website, 1000);
                                if (reply != null)
                                {
                                    roundTripTimes.Add(reply.RoundtripTime);
                                }
                            }
                            catch
                            {
                                Console.WriteLine("ERROR: You have some TIMEOUT issue");
                            }
                        }
                        writer.WriteLine("{0} , {1}", website, string.Join(" , ", roundTripTimes));
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

但是最好学习一些LINQ(例如LINQ 101)并以一种不那么冗长的方式编写代码,像这样:

using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
namespace ConsoleApplication1 
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var lstWebSites = new List<string>
            {
                "www.yahoo.com",
                "www.att.com",
                "www.verizon.com"
            };
            var filename = @"PingLog.csv";
            var pings = Enumerable.Range(0, 4).SelectMany(_ => lstWebSites.Select(ws => new {Ping = new Ping(), WebSite = ws}));
            var result = pings.Select(_ => new {Reply = _.Ping.Send(_.WebSite, 1000), _.WebSite}).ToLookup(_ => _.WebSite, p => p.Reply.RoundtripTime);
            using (var writer = new StreamWriter(filename, true))
            {
                foreach (var res in result)
                {
                    writer.WriteLine("{0}, {1}", res.Key, string.Join(" , ", res));
                }
            }
            Console.ReadKey();
        }
    }
}

此示例缺少异常处理,但您可以理解其主要思想。