C#获取程序的当前路径,启动和关闭一个Process

C#代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppProxy
{
    class RunProgram
    {
        static void Main(string[] args)
        {
            //System.Environment.CurrentDirectory 可执行程序文件的程序(exe程序)运行的启动完整路径
            //System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 控制台程序的可执行文件的文件名(包括完整路径)
            //string filePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string filePath = System.Environment.CurrentDirectory;
            Console.WriteLine("Curent file path: " + filePath);
            string agentExe = filePath + "\\..\\..\\..\\ConsoleApp\\bin\\Debug\\ConsoleApp.exe";
            Console.WriteLine(agentExe);

            Console.WriteLine("Starting a new console application--'ConsoleApp'");
            var startInfo = new ProcessStartInfo(agentExe);
            var proc = Process.Start(startInfo);
            System.Threading.Thread.Sleep(10000);
            Console.WriteLine("Stop 'ConsoleApp'");
            //proc.Kill();
            KillOneProcess("consoleapp");
            Console.WriteLine("'ConsoleApp' has been sotpped");
            Console.ReadLine();
        }

        private static void KillOneProcess(string procName)
        {
            Process[] procs = Process.GetProcesses();//获取已开启的所有进程

            //遍历所有查找到的进程

            for (int i = 0; i < procs.Length; i++)
            {

                //判断此进程是否是要查找的进程
                if (procs[i].ProcessName.ToString().ToLower() == procName)
                {
                    procs[i].Kill();//结束进程
                }
            }


        }
    }
}



被启动和关闭的程序的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Console App is running.");
            Console.ReadLine();
        }
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值