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

来源:互联网 发布:vs php 扩展 编辑:程序博客网 时间:2024/06/06 16:49

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();        }    }}






0 0