Ping a website and save the data in an .csv file - c#

When the code is RUN it has to ping the websites I specify 4 times each and then write the results in a .csv file. But I'm keep getting a TIMEOUT error. Can anyone tell me why? I tried so many different things and noting is working so far. Please help me out.
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");
}
}
}
}
}
}
}

Here's a working example. I added some comments where you had syntax errors or where I made adjustments to your original code.
// 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");
}
}

Ok I have most of this figured out. Thank you all so much for helping me.
Although, I still need this to ping at least three more websites and give me 4 ping results per website.
So if someone could please, please just help me out a little bit more.
Here is what I have and this so far it works:
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");
}
}
}
}
}
}

Related

I want to read content of 10 different website and save them into 10 diferrent text files

I have been able to read the content of a web page and saved it into a file. This question is, how do I read for 10 different webpages without having to repeat the code over and over again. Is there a loop mechanism that can help? Here is what I have done:
static void Main(string[] args)
{
Task Task1 = new Task(() => ReadWriteWeb("http://www.hawaii.edu"));
Task1.Start();
Console.ReadLine();
}
static void ReadWriteWeb(string Url)
{
try
{
using (WebClient WebC = new WebClient())
{
string WebContents = WebC.DownloadString(Url);
Console.WriteLine(WebContents);
using (StreamWriter SW = new StreamWriter("myFile")
SW.WriteLine(WebContents + ". " + "The lenght of file is {0}", WebContents.Length);
}
}
catch (Exception e)
{
Console.WriteLine("The web content cannot be reached");
Console.WriteLine(e.Message);
}
}
Forgive me, but assuming you are aware of loops already as I hope you are here is an the answer I thought you would be looking for. This will download all the files simultaneously via a simple loop / multithreaded feature of linq.
public class Program
{
volatile static int fileNameCounter = 1;
static void Main(string[] args)
{
var listOfTasks = new List<Task>()
{
new Task(() => ReadWriteWeb("http://www.hawaii.edu")),
new Task(() => ReadWriteWeb("http://www.hawaii.edu")),
new Task(() => ReadWriteWeb("http://www.hawaii.edu")),
new Task(() => ReadWriteWeb("http://www.hawaii.edu"))
};
listOfTasks.AsParallel().ForAll(task => task.Start());
Console.ReadLine();
}
static async void ReadWriteWeb(string Url)
{
Console.WriteLine($"File {fileNameCounter} complete");
try
{
using (WebClient WebC = new WebClient())
{
string WebContents = await WebC.DownloadStringTaskAsync(Url);
Console.WriteLine(WebContents);
using (StreamWriter SW = new StreamWriter($"myFile{fileNameCounter++}"))
SW.WriteLine(WebContents + ". " + "The lenght of file is {0}", WebContents.Length);
}
}
catch (Exception e)
{
Console.WriteLine("The web content cannot be reached");
Console.WriteLine(e.Message);
}
}
}
Since I only had the one web url I listed the same one 4 times. You get the idea...
Standard looping constructs in C# include the for loop and the foreach loop.
In general, anything you could possibly want to know about C# can be found in the reference on MSDN.

import Csv file Oledb C#

Hi please can anyone give me solution to this problem,i have to import csv file using c# but i have this problem in this screenshot
Screen
the separate betwenn column is ',' but in the data there is a rows tha contains ".
Mohamed, I cannot see your screenshot, but can point you toward generic lists and creating a class to represent data. You will need to add references from the "Project" menu.
Microsoft.VisualBasic
System.Configuration
WindowsBase
I am including code from a snippet of code where I was doing that:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.FileIO;
namespace CsvToListExp
{
class Program
{
public static void Main(string[] args)
{
// HARD_CODED FOR EXAMPLE ONLY - TO BE RETRIEVED FROM APP.CONFIG IN REAL PROGRAM
string hospPath = #"C:\\events\\inbound\\OBLEN_COB_Active_Inv_Advi_Daily_.csv";
string vendPath = #"C:\\events\\outbound\\Advi_OBlen_Active_Inv_Ack_Daily_.csv";
List<DenialRecord> hospList = new List<DenialRecord>();
List<DenialRecord> vendList = new List<DenialRecord>();
//List<DenialRecord> hospExcpt = new List<DenialRecord>(); // Created at point of use for now
//List<DenialRecord> vendExcpt = new List<DenialRecord>(); // Created at point of use for now
using (TextFieldParser hospParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(hospPath))
{
hospParser.TextFieldType = FieldType.Delimited;
hospParser.SetDelimiters(",");
hospParser.HasFieldsEnclosedInQuotes = false;
hospParser.TrimWhiteSpace = true;
while (!hospParser.EndOfData)
{
try
{
string[] row = hospParser.ReadFields();
if (row.Length <= 7)
{
DenialRecord dr = new DenialRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
hospList.Add(dr);
}
}
catch (Exception e)
{
// do something
Console.WriteLine("Error is: {0}", e.ToString());
}
}
hospParser.Close();
hospParser.Dispose();
}
using (TextFieldParser vendParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(vendPath))
{
vendParser.TextFieldType = FieldType.Delimited;
vendParser.SetDelimiters(",");
vendParser.HasFieldsEnclosedInQuotes = false;
vendParser.TrimWhiteSpace = true;
while (!vendParser.EndOfData)
{
try
{
string[] row = vendParser.ReadFields();
if (row.Length <= 7)
{
DenialRecord dr = new DenialRecord(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
vendList.Add(dr);
}
}
catch (Exception e)
{
// do something
Console.WriteLine("Error is: {0}", e.ToString());
}
}
vendParser.Close();
vendParser.Dispose();
}
// Compare the lists each way for denials not in the other source
List<DenialRecord> hospExcpt = hospList.Except(vendList).ToList();
List<DenialRecord> vendExcpt = vendList.Except(hospList).ToList();
}
}
}
Google TestFieldParser and look at the methods, properties and constructors. It is very versatile, but runs slowly due to the layers it goes through. It has the ability to set the delimiter, handle fields wrapped in quotes, trim whitespace and many more.

Anonymous Pipe not ending stream?

Hello I am having a strange error with using pipes to communicate between two process. In short everything is working fine with the program except that the client side never closes the stream, meaning the server's streamReader.readLine never returns null, causing the sever process to never terminate. I'm convinced this is a simple issue but I and struggling to find a answer. Here is some relevant code:
Server Side:
using (StreamReader sr = new StreamReader(clientServer))
{
// Display the read text to the console
string temp;
int count = 0;
while ((temp = sr.ReadLine()) != null)
{
if (count == 0)
{
Console.WriteLine("==========Parent Process found text:like==========");
}
Console.WriteLine(temp);
count++;
}
Console.WriteLine("out of while loop");
}
Client Project:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
class PipeClient
{
static void Main(string[] args)
{
try
{
if (args.Length < 3)
{
Console.WriteLine("Invalid number of commandline arguments");
}
else
{
List<string> inputList = new List<string>();
List<string> foundMatchList = new List<string>();
using (PipeStream pipeClientIn =
new AnonymousPipeClientStream(PipeDirection.In, args[0]))
{
using (StreamReader sr = new StreamReader(pipeClientIn))
{
// Display the read text to the console
string temp;
int count = 0;
while ((temp = sr.ReadLine()) != null)
{
if (count == 0)
{
Console.WriteLine("==========Client Process Read Text:==========");
}
Console.WriteLine(temp);
inputList.Add(temp);
count++;
}
foreach (var curtString in inputList)
{
if (curtString.Contains(args[2]))
{
foundMatchList.Add(curtString);
}
}
}
//Console.WriteLine("released sr");
}
// Console.WriteLine("released pipeClientIn");
using (PipeStream pipeClientOut =
new AnonymousPipeClientStream(PipeDirection.Out, args[1]))
{
using (StreamWriter sw = new StreamWriter(pipeClientOut))
{
sw.AutoFlush = true;
foreach (var match in foundMatchList)
{
sw.WriteLine(match);
}
}
}
//Console.WriteLine("released pipeClientOut");
}
}
catch (Exception e)
{
/* if (args.Length == 0)
Console.WriteLine("no arguments");
foreach(String s in args)
{
Console.Write("{0} ", s);
}*/
Console.WriteLine(e.Message);
}
}
}
I've tested and can confirm that the client process terminates.
I attempted to manually flush and close the Client StreamWriter but this did not work.
My overall question is: Why am I never seeing the the "out of while loop" message? And how can fix my client so that it will end the stream?
Did you call clientServer.DisposeLocalCopyOfClientHandle()?
from msdn
The DisposeLocalCopyOfClientHandle method should be called after the
client handle has been passed to the client. If this method is not
called, the AnonymousPipeServerStream object will not receive notice
when the client disposes of its PipeStream object.
hope this helps

.net remoting, How to reconnect if the connect is lost?

I have this working but i don't understand how to predict when the connection has dropped and needs to reconnect to the server.
what i want to do is have the client connect right away to the .net remoting server if it drops out, sort of like keep trying to connect and disregard if it does not need to.
help appreciated.
here is my code:
namespace TaskClient
{
using System;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Threading;
using TaskShared;
class Program
{
static void Main(string[] args)
{
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan, false);
Connections remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
if (remObject == null)
{
Console.WriteLine("Could not connect to TaskServer. (tcp://localhost:8085/TaskServer)");
}
else
{
Console.WriteLine("Connected to Task Server.");
var rt = new TestTask()
{
ApplicationName = Assembly.GetExecutingAssembly().FullName,
ComputerName = Environment.MachineName,
VersionInfo = "1.0.0",
JobRunning = "None"
};
remObject.Add(rt);
}
while (true)
{
//TODO:
//Check if connected.. how?
//Re-create the connection... how?
//doing this simple won't work:
if (remObject == null)
remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
remObject.Invalidate(remObject[rt]);
Thread.Sleep(1000);
}
}
}
}

DownloadFileAsync multiple files using webclient

Description
Download multiple files using webclient's DownloadFileAsync and utilizing a text file for URL input for download.
Problem
The approach that I have used won't download files at all. Just runs and does nothing. It fills the list array then quits the program without downloading a single file. I have googled for solutions but come up shorthanded. Then attempted to search for a solution in the database here with same results. Any help is appreciated.
Questions
Why does this approach not work?
What can I do to improve this and learn from this.
Code
DownloadClass.cs
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Windows.Forms;
namespace ThreadTest
{
class DownloadClass
{
public struct download
{
public static string URL { get; set; }
public static string file { get; set; }
public static string[] link;
public static int downloadcount;
}
public static List<string> list = new List<string>();
public static WebClient wc = new WebClient();
public static void Download()
{
int count = 0;
download.URL = list[0];
Uri URI = new Uri(download.URL);
UriBuilder uri = new UriBuilder(URI);
download.link = uri.Path.ToLower().Split(new char[] { '/' });
count = 0;
// Find file
foreach (string abs in download.link)
{
count++;
if (abs.ToLower().Contains(".html") || abs.ToLower().Contains(".exe") || abs.ToLower().Contains(".txt"))
{
try
{
download.file = download.link[count];
wc.Proxy = null;
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync(URI, Application.StartupPath + "\\" + download.file);
break;
}
catch (Exception)
{ }
}
}
}
public static void BeginDownload()
{
new Thread(Download).Start();
}
public static void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
int count = 0;
download.downloadcount++;
download.URL = list[0];
Uri URI = new Uri(download.URL);
UriBuilder uri = new UriBuilder(URI);
download.link = uri.Path.ToLower().Split(new char[] { '/' });
count = 0;
// Find file
foreach (string abs in download.link)
{
count++;
if (abs.ToLower().Contains(".html") || abs.ToLower().Contains(".exe") || abs.ToLower().Contains(".txt"))
{
try
{
download.file = download.link[count];
}
catch (Exception)
{ }
}
}
list.RemoveAt(0);
if (list.Count > 0)
{
wc.DownloadFileAsync(URI, list[download.downloadcount], Application.StartupPath + "\\" + download.file);
}
else
{
Console.WriteLine("Downloading is done.");
Environment.Exit(0);
}
}
}
}
Program.cs (Main Class)
using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: {0} <download txtfile>", Environment.GetCommandLineArgs()[0]);
Environment.Exit(0);
}
int counter = 0;
string line;
string format = string.Format("{0}\\{1}", Application.StartupPath, args[0]);
// Read the file line by line.
using(StreamReader file = new StreamReader(format))
{
while ((line = file.ReadLine())!= null)
{
// Store urls in a list.
DownloadClass.list.Add(line);
counter++;
}
}
DownloadClass.BeginDownload();
}
}
}
Besides being bad design there are lots of issues that lead to your code not (or nor correctly working).
You need to make sure that you application lives while it downloads something. Your current app quits right away (you have to wait for the downloading to complete in your main).
You application may download the same file multiple times but not download others at all (You need to completely lock object when they are used in an async=multithreading way like here when accessing static objects) BTW: Don't use static objects at all to avoid that in the first place.
Even if 2 is corrected it may still download the same file multiple times into the same filename and thus fail.
As long as you have no knowledge about multithreading I'd recommend you use the synchoneous methods to avoid all those problems.

Categories

Resources