C# 获取网关地址 读取配置文件 打开关闭exe

时间:2021-02-12 23:49:27

C#好久好久没去用过了,今早写了个C#小程序, 链接手机热点,然后根据发过来的信息去读取配置文件,将配置文件中相应的exe重启,即先关闭后启动.

里面涉及到的一些小块我在这里记录下.


1, 获取链接的手机热点的网关

//得到网关地址
private static string GetGateway()
{
        string strGateway = "";

        //获取所有网卡
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

        foreach (var netWork in nics)
        {
                IPInterfaceProperties ip = netWork.GetIPProperties();
                //获取该IP对象的网关
                GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;

                foreach (var gateWay in gateways)
                {
                        if (IsPingIP(gateWay.Address.ToString()))
                        {
                                strGateway = gateWay.Address.ToString();
                                break;
                        }
                }
                if (strGateway.Length > 0)
                {
                        break;
                }
        }
        return strGateway;
}

public static bool IsPingIP(string strIP)
{
        try
        {
                Ping ping = new Ping();
                PingReply reply = ping.Send(strIP, 1000);
                return true;
        }
        catch
        {
                return false;
        }
}




2, 读取配置文件
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault,
        StringBuilder lpReturnedString, int nSize, string lpFileName);


// 读取配置文件
private static string ReadINIString(string section, string key, string def, string filePath)
{
        StringBuilder temp = new StringBuilder(1024);
        try
        {
                GetPrivateProfileString(section, key, def, temp, 1024, filePath);
        }
        catch { }
        return temp.ToString();
}




3.打开关闭exe
// 关闭exe
Process[] allProgresse = Process.GetProcesses();
foreach (Process closeProgress in allProgresse)
{
        if (closeProgress.ProcessName.Equals(sname))
        {
                closeProgress.Kill();
                closeProgress.WaitForExit();
                break;
        }
}

// 打开exe
System.Diagnostics.Process.Start(sPath);