2010-08-06 83 views
2

我有一个接受Cmd命令作为命令参数的程序。将Cmd命令传递给C#应用程序

基本上你怎么称呼它是这样的:C:\MyProgram.exe del C:\test.txt

上面的命令工作正常。然而,当我尝试做一个xcopy命令失败:

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

程序的代码:

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; 
    } 
} 
+0

执行xcopy命令时是否存在C:\ test.txt? – 2010-08-06 18:17:25

+0

它如何失败?它给了什么错误? – David 2010-08-06 18:18:18

+0

@Jimmy是的,上面的目录是由一个构成的,但是在我们真正的目录存在的程序调用中。 – mint 2010-08-06 18:18:33

回答

2

我认为Jimmy Hoffa的答案是正确的,要解决它,您可以在命令的开始时将cocatenate“开始”。

xcopy C:\ temp \ test.html C:\ temp \ test2.html将在需要时为您带来一个提示窗口。

+0

加入开始做到了。非常感谢! ps jimmy我upvoted你,我的选票jonathan,我会upvote你,当我可以。 – mint 2010-08-06 18:30:00

+0

谢谢! (我讨厌在评论中的15个字符限制!) – Jonathan 2010-08-06 18:32:05

6

我认为您的应用程序工作,所以我尝试的命令,只是有这个提示从标准输入:

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)? 

也许是因为轰炸您没有标准输入追平,而且您的应用才刚刚返回从执行的返回码。

相关问题