Ping一个网站并将数据保存在.csv文件中
问题描述:
当代码为RUN时,它必须对我指定的网站进行四次ping操作,然后将结果写入.csv文件。但我不断收到TIMEOUT错误。谁能告诉我为什么?我尝试了很多不同的东西,注意到目前为止工作。请帮助我。Ping一个网站并将数据保存在.csv文件中
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");
string filename = @"PingLog.csv";
{
using (var writer = new StreamWriter(filename, true))
{
foreach(string website in lstWebSites)
{
writer.WriteLine(website);
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(website, 1000);
if (reply != null)
{
Console.WriteLine("{0}, {1}", reply.Address, reply.RoundtripTime);
}
}
catch
{
Console.WriteLine.("ERROR: You have some TIMEOUT issue");
}
}
}
}
}
}
}
答
好吧我大部分都想通了。非常感谢你帮助我。 虽然,我仍然需要这个ping至少三个网站,并给我每个网站4 ping结果。所以如果有人可以请,请多帮我一点。 下面是我所拥有的和迄今为止它的工作原理:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace Ping Application
{
class Program
{
static void Main(string[] args)
{
string filename = @"PingLog.csv";
{
using (var writer = new StreamWriter(filename, true))
{
writer.WriteLine("www.yahoo.com", Time in MilliSeconds);
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send("www.yahoo.com", 1000);
if (reply != null)
{
Console.WriteLine("{0}, {1}, {2}", reply.Address, reply.RoundtripTime, reply.RoundtripTime);
}
}
catch
{
Console.WriteLine.("ERROR: You have some TIMEOUT issue");
}
}
}
}
}
}
答
下面是一个工作示例。我添加了一些评论,你有语法错误或我对原始代码进行了调整。
// Missing quotes, should probably be a full file path
string filename = @"C:\temp\PingLog.csv";
// You had an extra opening brace here
// Open a file for writing using the filename, and a flag that means whether to append
using (var writer = new StreamWriter(filename, false))
{
// Write a CSV header
writer.WriteLine("Status, Time, Address");
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send("www.yahoo.com", 1000);
if (reply != null)
{
// Use the overload of WriteLine that accepts string format and arguments
writer.WriteLine("{0}, {1}, {2}", reply.Status, reply.RoundtripTime, reply.Address);
}
}
catch
{
// You had a syntax error here
Console.WriteLine("ERROR: You have some TIMEOUT issue");
}
}
输出是什么? – horns
什么是错误? –
上述代码中存在语法错误。你在使用IDE吗?你错过了文件名的引号,并且你使用了一个名为'stream'的变量而没有声明过它 –