Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get your PING and put it on a label

Tags:

c#

winforms

ping

I was trying to find how to get my ping and found this code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.IO;
using System.Configuration;
using System.Web;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Ping ping = new Ping();
                PingReply pingreply = ping.Send("www.google.com");
                StreamWriter sw = new StreamWriter(@"C:\ping.txt");
                StringBuilder sb = new StringBuilder();
                sb.Append("Address: " + pingreply.Address + "\r\n");
                sb.Append("Roundtrip Time: " + pingreply.RoundtripTime + "\r\n");
                sb.Append("TTL (Time To Live): " + pingreply.Options.Ttl + "\r\n");
                sb.Append("Buffer Size: " + pingreply.Buffer.Length.ToString() + "\r\n");
                sb.Append("Time : " + DateTime.Now + "\r\n");
                sw.Write(sb.ToString());
                sw.Close();
            }
            catch (Exception err)
            {
            }
        }
    }
}

I tried to do something like this:

label1.Text = pingreply.Buffer.Length.ToString();

But it didn't work to get the ping, and i can't figure out how to get it on a label, does anyone know how to do this?

like image 591
Dozer789 Avatar asked Dec 21 '22 10:12

Dozer789


1 Answers

You are catching all errors and ignoring them.. probably caused by your attempt at writing it to a file.

Just do this:

label1.Text = new Ping().Send("www.google.com").RoundtripTime.ToString() + "ms";

Or, properly disposing (thanks @Ichabod Clay)

using (Ping p = new Ping()) {
    label1.Text = p.Send("www.google.com").RoundtripTime.ToString() + "ms";
}
like image 135
Simon Whitehead Avatar answered Dec 22 '22 22:12

Simon Whitehead