Passing Cmd Command to C# Application

橙三吉。 提交于 2021-01-27 23:16:30

问题


I have a program that accepts a Cmd command as a command argument.

Basically you call it this way: C:\MyProgram.exe del C:\test.txt

The above command works fine. However when I try to do an xcopy command it fails:

C:\MyProgram.exe xcopy C:\test.txt C:\Temp\Test2.txt

The code of the program:

class Program
{
    static void Main(string[] args)
    {
        string command = GetCommandLineArugments(args);

        // /c tells cmd that we want it to execute the command that follows and then exit.
        System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", @"/D /c " + command);

        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;

        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        process.StartInfo = procStartInfo;
        process.Start();
    }

    private static string GetCommandLineArugments(string[] args)
    {
        string retVal = string.Empty;

        foreach (string arg in args)
            retVal += " " + arg;

        return retVal;
    }
}

回答1:


I think Jimmy Hoffa answer is right, to solve it you can cocatenate "start " at the beggining of the command.

xcopy C:\temp\test.html C:\temp\test2.html will bring you a window with a prompt when needed.




回答2:


I think your application is working, so I tried the command and just got this prompt for input from stdin:

C:\>xcopy C:\temp\test.html C:\temp\test2.html
Does C:\temp\test2.html specify a file name
or directory name on the target
(F = file, D = directory)?

Perhaps it's bombing because you don't have the stdin tied in, and your app is just returning the return code from the execution.



来源:https://stackoverflow.com/questions/3426542/passing-cmd-command-to-c-sharp-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!