C# 运行指定程序,可以方便扩展

本文介绍了一个程序,用于处理命令行参数,检查文件是否存在,查找并终止同名运行进程,然后根据需要运行指定批处理脚本。该程序通过控制台输出详细信息,包括错误处理、文件状态和进程管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要测试代码:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace CallBat
{
	/// <summary>
	/// 作者:Jave.Lin
	/// </summary>
	static class Program
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//Application.EnableVisualStyles();
			//Application.SetCompatibleTextRenderingDefault(false);
			//Application.Run(new Form1());
			if (args.Length == 0)
			{
				Console.WriteLine("args.Length==0 error!");
				return;
			}
			string fileName = args[0];
			if (!File.Exists(fileName))
			{
				Console.WriteLine("fileName is not Exists error! the fileName is:\r\n"+fileName);
				return;
			}
			string fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName);
			Process[] tps = Process.GetProcessesByName(fileNameNoExtension);
			if (tps != null)
			{
				foreach (Process tp in tps)
				{
					if (tp.ProcessName == fileNameNoExtension)
					{
						try
						{
							Console.WriteLine("[" + fileNameNoExtension + "] process had run, and then will kill it!");
							tp.Kill();
							tp.Close();
						}
						catch
						{ }
					}
				}
			}

			string workDirectory = Path.GetDirectoryName(fileName);

			System.Diagnostics.Process p = new System.Diagnostics.Process();
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.CreateNoWindow = true;//设置为false将会看到程序窗口 
			p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//启动进程时窗口状态 
			p.StartInfo.RedirectStandardOutput = true;
			//p.StartInfo.FileName = Server.MapPath("a.bat"); 
			p.StartInfo.FileName = fileName;//如果a.bat在System32文件夹中,此处只需填写文件名即可
			p.StartInfo.WorkingDirectory = workDirectory;
			if (args.Length > 1)
			{
				string argsStr = string.Empty;
				for (int i = 1; i < args.Length; i++)
				{
					argsStr += args[i] + " ";
				}
				p.StartInfo.Arguments = argsStr;
			}
			
			p.Start();
			p.Close(); 
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值