简体   繁体   English

使用C#中的参数运行批处理文件

[英]Running batch file with arguments from C#

I have a batch file like this 我有这样的批处理文件

@echo off
xcopy /e %1 %2

I have my C# code as follows: 我有我的C#代码如下:

string MyBatchFile = @"C:\Program Files (x86)\MybatchFile.bat";
string _sourcePath = @"C:\FolderToCopy";
string _tempTargetPath = @"C:\TargetFolder\";

var process = new Process { 
                   StartInfo = { 
                      Arguments = string.Format("{0} {1}",
                                                _sourcePath,
                                                _tempTargetPath) 
                                } 
                          };
process.StartInfo.FileName = MyBatchFile;
bool b = process.Start();

I expect this to copy the source files to target location. 我希望这会将源文件复制到目标位置。 But nothing happens. 但没有任何反应。 My console window also does not stay for enough time so that I can see the error. 我的控制台窗口也没有停留足够的时间,以便我可以看到错误。 Can anyone guide to achieve this. 任何人都可以指导实现这一点。 I am new in batch files processing. 我是批处理文件处理的新手。

Edit 编辑

By adding a pause in the end of batch file. 通过在批处理文件的末尾添加pause Able to reproduce error. 能够重现错误。 Getting error as 得到错误

Files not found - Program

Running batch file directly does work fine. 直接运行批处理文件可以正常工作。 Just now noticed......when source path has any spaces....I am getting error 刚才注意到......当源路径有任何空格......我收到错误

引用参数怎么样?

Arguments = String.Format("\"{0}\" \"{1}\"", _sourcePath, _tempTargetPath) …

.bat file is a text file, in order to execute it, you should start cmd process. .bat文件是一个文本文件,为了执行它,你应该启动cmd进程。 Start it like this: 像这样开始:

System.Diagnostics.Process.Start("cmd.exe", "/c yourbatch.bat");

Additional arguments may follow. 可能会有其他论点。 Try this without c#, in a cmd window, or Run dialog. 在没有c#的情况下,在cmd窗口或“运行”对话框中尝试此操作。

try 尝试

string MyBatchFile = @"C:\MybatchFile.bat";
string _sourcePath = @"C:\FolderToCopy\*.*";
string _tempTargetPath = @"C:\TargetFolder\";

ie add *.* to the source path 即将*.*添加到源路径

and add a 3rd line pause to the batch file 并在批处理文件中添加第3行pause

@echo off
copy /e %1 %2
pause

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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