C# 1.Winform 同时修改多个config文件2.实时监测某程序运行状态(多线程),未启动时,自启。

一、功能描述

功能1:同时修改多个config文件:

.①E:\Files\test.config②E:\Files\test1\test.config③E:\Files\test2\test.config中的test.config文件中都包含有如下节点

<configuration>
  <H262.Connector>
    <ClientSettings>
      <add NAME="Conn" USER="admin" PASSWD="123456" VALUE="192.168.10.150" LANG="ZH">
      </add>
    </ClientSettings>
  </H262.Connector>
</configuration>
点击按钮实现同时修改3个test.config中的 
USER="admin" PASSWD="123456" VALUE="192.168.10.150"

功能2:timer监测QQ、微信 运行状态 每隔1秒显示,如果程序未启动,自启。

功能3:QQ、微信 两个程序各自开一个线程。

功能4:读取APP.config中配置的值到后台使用。

二、界面:


三、代码如下:

1.Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public XmlNode Node;
        public string FileName;
        XmlDocument xmlDoc = new XmlDocument();
        public string rootPathConfig = ConfigurationManager.AppSettings["RootPathConfig"];
        public string timeInterval = ConfigurationManager.AppSettings["TimeInterval"];
        public Form1()
        {
            InitializeComponent();
            rdbQQClose.Checked = true;
            rdbWeChatClose.Checked = true;
            RunningState();
            timer1.Interval = int.Parse(timeInterval);
            timer1.Start();
            CheckForIllegalCrossThreadCalls = false;//限制(线程必须添加此行)

        }
        #region 文件配置
        public void LoadMain()
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(rootPathConfig);//指定文件夹下循环某个文件。
                foreach (FileInfo file in dir.GetFiles("*.config", SearchOption.AllDirectories))//第二个参数表示搜索包含子目录中的文件
                {
                    if (file.Name.Contains("test"))
                    {
                        FileName = file.Name;
                        string path = file.FullName;
                        xmlDoc.Load(path);
                    }
                }
                Node = xmlDoc.SelectSingleNode("configuration/H262.Connector/ClientSettings/add");//节点地址
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件出错!" + ex);
            }
        }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetConfig_Click(object sender, EventArgs e)
        {
            LoadMain();
            if (Node != null)
            {
                txtUser.Text = Node.Attributes["USER"].InnerText;
                txtPwd.Text = Node.Attributes["PASSWD"].InnerText;
                txtIP.Text = Node.Attributes["VALUE"].InnerText;
            }
            else
            {
                MessageBox.Show("无法找到该路径下文件!");
                Clear();
            }
        }
        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateConfig_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtUser.Text) || !String.IsNullOrEmpty(txtPwd.Text) || !String.IsNullOrEmpty(txtIP.Text))
            {
                Node.Attributes["USER"].InnerText = txtUser.Text;
                Node.Attributes["PASSWD"].InnerText = txtPwd.Text;
                Node.Attributes["VALUE"].InnerText = txtIP.Text;
                
                DirectoryInfo dir = new DirectoryInfo(rootPathConfig);
                foreach (FileInfo file in dir.GetFiles("*.config", SearchOption.AllDirectories))//第二个参数表示搜索包含子目录中的文件
                {
                    if (file.Name.Contains("test"))
                    {
                        FileName = file.Name;
                        string path = file.FullName;
                        //保存覆盖到原文件
                        xmlDoc.Save(path);
                    }
                }
                MessageBox.Show("修改成功!");
                Clear();
            }
            else
            {
                MessageBox.Show("修改信息不能为空!");
            }
        }
        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearAllTxt_Click(object sender, EventArgs e)
        {
            Clear();
        }
        public void Clear()
        {
            foreach ( Control ctr in groupBox1.Controls)
            {
                if (ctr is TextBox)
                {
                    ctr.Text = "";
                }
            }
        }
        #endregion

        #region 运行状态
        #region 运行状态 方法1 单选按钮形式
        
        /// <summary>
        /// 运行状态
        /// </summary>
        public void RunningState()
        {
            if (Process.GetProcessesByName("QQ").ToList().Count > 0)
            {
                //存在
                rdbQQOpen.Checked = true;
            }
            else
            {
                //不存在
                rdbQQClose.Checked = true;
            }
            if (System.Diagnostics.Process.GetProcessesByName("WeChat").ToList().Count > 0)
            {
                rdbWeChatOpen.Checked = true;
            }
            else
            {
                rdbWeChatClose.Checked = true;
            }
        }
        /// <summary>
        /// 一键启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartup_Click(object sender, EventArgs e)
        {
            if (Process.GetProcessesByName("QQ").ToList().Count > 0)
            {
                //存在
                rdbQQOpen.Checked = true;
            }
            else
            {
                //不存在
                rdbQQClose.Checked = true;
                //自动开启QQ
                Process p = new Process();
                p.StartInfo.FileName = " E:\\QQ\\Tencent\\QQ\\Bin\\QQ.exe";
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            if (System.Diagnostics.Process.GetProcessesByName("WeChat").ToList().Count > 0)
            {
                rdbWeChatOpen.Checked = true;
            }
            else
            {
                rdbWeChatClose.Checked = true;
                //自动开启微信
                Process p = new Process();
                p.StartInfo.FileName = "E:\\Program Files (x86)\\Tencent\\WeChat\\WeChat.exe";
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            RunningState();
            //文本框显示程序运行状态
        }
        #endregion
        #region 运行状态方法2 实时timer监测形式 创建两个线程
        /// <summary>
        /// 每隔1秒检测进程是否存在该程序进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            //创建两个线程
            Thread thread = new Thread(RunQQ);
            thread.Start();
            Thread thread2 = new Thread(RunWeChat);
            thread2.Start();
            //timer1.Stop();
        }
        private void RunQQ()
        {
            string DateTimeStr = "当前时间:" + System.DateTime.Now.ToString() + "\t";
            string processname = "QQ";
            if (Process.GetProcessesByName(processname).Length > 0)
            {
                rdbQQOpen.Checked = true;
                this.textBox1.AppendText(DateTimeStr + "运行状态:Q  Q运行中……" + "\r\n");
            }
            else
            {
                rdbQQClose.Checked = true;
                this.textBox1.AppendText(DateTimeStr + "运行状态:Q  Q已关闭……" + "\r\n");
                //自动开启QQ
                Process p = new Process();
                p.StartInfo.FileName = " E:\\QQ\\Tencent\\QQ\\Bin\\QQ.exe";
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            textBox1.ScrollToCaret();//将控件滚动到当前插入符号位置
        }
        private void RunWeChat()
        {
            string DateTimeStr = "当前时间:" + System.DateTime.Now.ToString() + "\t";
            string processname1 = "WeChat";
            if (Process.GetProcessesByName(processname1).Length > 0)
            {
                rdbWeChatOpen.Checked = true;

                this.textBox1.AppendText(DateTimeStr + "运行状态:微信运行中……" + "\r\n");
            }
            else
            {
                rdbWeChatClose.Checked = true;

                this.textBox1.AppendText(DateTimeStr + "运行状态:微信已关闭……" + "\r\n");
                //自动开启微信
                Process p = new Process();
                p.StartInfo.FileName = "E:\\Program Files (x86)\\Tencent\\WeChat\\WeChat.exe";//此处可以优化为从注册表中得到该程序路径
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            textBox1.ScrollToCaret();//将控件滚动到当前插入符号位置
        }
        #endregion

        #endregion
    }
}

2.App.config代码:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

  <appSettings>
    <!--配置跟目录-->
    <add key="RootPathConfig" value="E:\Files\"/>
    <!--状态读取的时间间隔-->
    <add key="TimeInterval" value="1000"/>
  </appSettings>

</configuration>

 提示: public string rootPathConfig = ConfigurationManager.AppSettings["RootPathConfig"];  

ConfigurationManager需要添加引用

第一次写,请各位大神谅解,代码未优化。

<!--学习就是不断积累的过程-->

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值