天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

104 lines
3.4 KiB

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace AutoFileCopyNet
{
public class Monitoring
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
private string IPAddress = null;
private System.Timers.Timer aTimer = new System.Timers.Timer();
private static int PingTime;
private static string constatus;
public void init()
{
aTimer.Interval = 1000;
aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
aTimer.Enabled = true;
}
//计时器事件
private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
{
if (!IsConnected())
{
WriteLog(0);
}
else
{
string Result = PingResult(IPAddress);
if (Result != "Success")
{
WriteLog(1);
}
}
}
//检测本机是否连接到互联网
private bool IsConnected()
{
int I = 0;
bool state = InternetGetConnectedState(out I, 0);
return state;
}
int i = 0;
//Ping IP地址, 返回TTL值.
private string PingResult(string ip)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "12345678901234567890123456789012";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1000;
System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
PingTime = int.Parse(reply.RoundtripTime.ToString());
constatus = reply.Status.ToString() + i.ToString();
i++;
return reply.Status.ToString();
}
private void WriteLog(int arg)
{
using (FileStream fs = new FileStream(@"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + IPAddress + ".txt", FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
switch (arg)
{
case 0:
m_streamWriter.WriteLine("NetWork Disconnection Time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n");
break;
case 1:
m_streamWriter.WriteLine("IPAddress Disconnection Time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n");
break;
default:
break;
}
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
}
public void TimesConsole()
{
if ("Enable" == "Enable")
{
if (!string.IsNullOrEmpty(IPAddress))
{
aTimer.Enabled = true;
}
}
else
{
aTimer.Enabled = false;
}
}
}
}