简体   繁体   中英

The system cannot find the file specified while running command through Process module in C#

I am trying to execute one command through process but it is throwing exception as "The system cannot find the file specified". When i run this command directly on command prompt. It is working fine.

Command: start cmd.exe @cmd /k "NTttcpr.exe -r -m 1,*,192.168.1.2 -a 2 -t 120 -wu 10 -cd 10 >> NTTTCP-1T-TCP-IPV4-Rx-MTU1500-Support-port-1-Rx-AMD-10-GBE-RJ45-ITR-1.log"

This command executes perfectly if i run on command prompt.

This is how i written code:

string tool = @"NTttcpr.exe";
string command = " -r -m 1,*,192.168.1.2 -a 2 -t 120 -wu 10 -cd 10 >> NTTTCP-1T-TCP-IPV4-Rx-MTU1500-Support-port-1-Rx-AMD-10-GBE-RJ45-ITR-1.log";

private void RunCommand(string tool, string command)
    {
        try
        {
            logger.Info($"{MethodBase.GetCurrentMethod()}: {tool} {command}");
            Process pro = new Process();
            pro.StartInfo.FileName = "start cmd ";
            pro.StartInfo.Arguments = "@cmd /k " + '"' + tool  + " " + command + '"';

            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardOutput = true;

            logger.Info($"{MethodBase.GetCurrentMethod()}: Executing command: {tool} {command}");
            pro.StartInfo.Verb = "runas";
            pro.Start();
            //pro.WaitForExit(MillisecondsTimeout);
            //Thread.Sleep(MillisecondsTimeout);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            logger.Error($"{MethodBase.GetCurrentMethod()}: Exception occurred while uni-directional command!!");
            logger.Error($"{MethodBase.GetCurrentMethod()}: {ex}");
        }
    }

Note: NTttcpr.exe file is already present in current executing directory.

Please help me to solve this.

This should be because you have not set the working directory, add pro.StartInfo.WorkingDirectory = "path to NTttcpr.exe" do not add NTttcpr.exe, just add the location.

Let me know if this works.

cmd.exe is not required for Process class. Try like below.

pro.StartInfo.FileName = "NTttcpr.exe";
pro.StartInfo.Arguments = command 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM