我写了一个利用PING的类的小程序做练习,实现实时统计响应时间的功能,并且在延时大于某个值时将时间写入文本,可是现在只能显示最后一次的结果。如何能在写入新的值时不覆盖上一次的呢?using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;enum ConnectionState : int
{
    INTERNET_CONNECTION_MODEM = 0x1,
    INTERNET_CONNECTION_LAN = 0x2,
    INTERNET_CONNECTION_PROXY = 0x4,
    INTERNET_RAS_INSTALLED = 0x10,
    INTERNET_CONNECTION_OFFLINE = 0x20,
    INTERNET_CONNECTION_CONFIGURED = 0x40
}
class ping
{[System.Runtime.InteropServices.DllImport("wininet", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern bool InternetGetConnectedState(ref ConnectionState lpdwFlags, 
                                             int dwReserved); static bool IsOffline()
{
    ConnectionState state = 0;
    InternetGetConnectedState(ref state, 0);
    if (((int)ConnectionState.INTERNET_CONNECTION_OFFLINE & (int)state) != 0)
    {
        return true;
    }    return false;
}
 static void StartPing(object argument)
{
    IPAddress ip = (IPAddress)argument;    //set options ttl=128 and no fragmentation
    PingOptions options = new PingOptions(128, true);    //创建一个Ping对象
    Ping ping = new Ping();    //32个空字节的缓冲区
    byte[] data = new byte[32];    int received = 0;
    System.Collections.Generic.List<long> responseTimes = new System.Collections.Generic.List<long>();    //ping 100 次
    for (int i = 0; i < 100; i++)
    {
        PingReply reply = ping.Send(ip, 1000, data, options);        if (reply != null)
        {
            switch (reply.Status)
            {
                case IPStatus.Success:
                    String str = reply.RoundtripTime.ToString();
                    int n = int.Parse(str);
                    if (n > 5)
                    {
                        Console.WriteLine(DateTime.Now.ToString());
                        Console.WriteLine("响应超时");
                        System.IO.FileStream aFile = new System.IO.FileStream("f:\\报告.txt", System.IO.FileMode.OpenOrCreate);
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(aFile);                        string text = " ";                        text = DateTime.Now.ToString() + "响应超时 " + Environment.NewLine;                        sw.Write(text);
                        sw.Close();
                        aFile.Close();
                       aFile.Dispose();
                       
                    }
                    Console.WriteLine("Reply from {0}: " + 
                        "bytes={1} time={2}ms TTL={3}",
                        reply.Address, reply.Buffer.Length, 
                        reply.RoundtripTime, reply.Options.Ttl);
                    received++;
                    responseTimes.Add(reply.RoundtripTime);
                    break;
                case IPStatus.TimedOut:
                    Console.WriteLine("Request timed out.");
                    break;
                default:
                    Console.WriteLine("Ping failed {0}", 
                                      reply.Status.ToString());
                    break;
            }
        }
        else
        {
            Console.WriteLine("Ping failed for an unknown reason");
        }
    }    //统计信息
    long averageTime = -1;
    long minimumTime = 0;
    long maximumTime = 0;    for (int i = 0; i < responseTimes.Count; i++)
    {
        if (i == 0)
        {
            minimumTime = responseTimes[i];
            maximumTime = responseTimes[i];
        }
        else
        {
            if (responseTimes[i] > maximumTime)
            {
                maximumTime = responseTimes[i];
            }
            if (responseTimes[i] < minimumTime)
            {
                minimumTime = responseTimes[i];
            }
        }
        averageTime += responseTimes[i];
    }    StringBuilder statistics = new StringBuilder();
    statistics.AppendFormat("Ping statistics for {0}:", ip.ToString());
    statistics.AppendLine();
    statistics.AppendFormat("   Packets: Sent = 4, " + 
        "Received = {0}, Lost = {1} <{2}% loss>,",
        received, 4 - received, Convert.ToInt32(((4 - received) * 100) / 4));
    statistics.AppendLine();
    statistics.Append("Approximate round trip times in milli-seconds:");
    statistics.AppendLine();    //在loss不为100%时显示
    if (averageTime != -1)
    {
        statistics.AppendFormat("    Minimum = {0}ms, " + 
            "Maximum = {1}ms, Average = {2}ms",
            minimumTime, maximumTime, (long)(averageTime / received));
    }    Console.WriteLine();
    Console.WriteLine(statistics.ToString());
    Console.WriteLine();
    Console.WriteLine("Press any key to exit.");
    Console.ReadLine();
}
static void Main(string[] args)
{
    string address = string.Empty;    if (args.Length == 0)
    {
        Console.WriteLine("PingDotNet needs a host or IP address, insert one");
        address = Console.ReadLine();
        Console.WriteLine();
    }
    else
    {
        address = args[0];
    }    if (IsOffline())
    {
        Console.WriteLine("No internet connection detected.");
        Console.WriteLine("Press any key to exit.");
        Console.ReadLine();
        return;
    }    IPAddress ip = null;
    try
    {
        ip = Dns.GetHostEntry(address).AddressList[0];
    }
    catch (System.Net.Sockets.SocketException ex)
    {
        Console.WriteLine("DNS Error: {0}", ex.Message);
        Console.WriteLine("Press any key to exit.");
        Console.ReadLine();
        return;
    }    Console.WriteLine("Pinging {0} [{1}] with 32 bytes of data:", 
                      address, ip.ToString());
    Console.WriteLine();
    System.Threading.Thread pingThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(StartPing));
    pingThread.Start(ip);
    pingThread.Join();
}
}

解决方案 »

  1.   

    这样写不会覆盖以前写的,你试试看           FileStream aFile = new FileStream("Barcode.txt", FileMode.OpenOrCreate);
                    //StreamWriter sw = new StreamWriter("Barcode.txt", false);
                    StreamWriter sw = new StreamWriter(aFile);
                    sw.WriteLine(DateTime .Today .ToString ());
                    sw.WriteLine(strBarcode,true );
                    sw.Close();
      

  2.   

    不行啊,现在连结果都没有了。写入的直接是文件名。
                               if (n > 5)
                        {
                            Console.WriteLine(DateTime.Now.ToString());
                            Console.WriteLine("响应超时");
                            System.IO.FileStream aFile = new System.IO.FileStream("f:\\报告.txt", System.IO.FileMode.OpenOrCreate);
                            //StreamWriter sw = new StreamWriter("Barcode.txt", false); 
                            System.IO.StreamWriter sw = new System.IO.StreamWriter(aFile);
                            sw.WriteLine(DateTime.Today.ToString());
                            sw.WriteLine("f:\\报告.txt", true);
                            sw.Close();
                           
                        }
    有什么错误吗?
      

  3.   

    原来写入的是2009-2-11 16:39:29响应超时 
    现在就有个日期,没有时间,也没有响应超时,只有f:\\报告。txt