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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14498206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:02:45  来源:igfitidea点击:

Running batch file with arguments from C#

c#batch-fileargumentsxcopy

提问by Sandy

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 pausein the end of batch file. Able to reproduce error. Getting error as

通过pause在批处理文件的末尾添加一个。能够重现错误。获取错误为

Files not found - Program

Running batch file directly does work fine. Just now noticed......when source path has any spaces....I am getting error

直接运行批处理文件可以正常工作。刚刚注意到......当源路径有任何空格时......我收到错误

采纳答案by Viacheslav Ivanov

What about quoting argument?

引用论证呢?

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

回答by qujck

try

尝试

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

i.e. add *.*to the source path

即添加*.*到源路径

and add a 3rd line pauseto the batch file

并将第三行添加pause到批处理文件中

@echo off
copy /e %1 %2
pause

回答by Vladimir Perevalov

.bat file is a text file, in order to execute it, you should start cmd process. Start it like this:

.bat 文件是一个文本文件,为了执行它,你应该启动 cmd 进程。像这样开始:

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 窗口或运行对话框中试试这个。