2010-09-23 61 views
0

我正在编写批处理文件并通过c#程序执行它。从C#程序执行BatchFile

编写批处理文件:

我会得到路径,可执行文件名和参数从app.config中,并将其写入到一个批处理文件。

执行批处理文件:

一旦我写批处理文件我通过文件名下面的功能,其执行批处理文件启动一个应用程序。

问题:

我的程序会写很多,它们分别后立即执行,每个文件被写入批处理文件。我发现,有些时候应用程序没有启动,这意味着批处理文件没有执行。我甚至得到任何错误消息或提示批处理文件执行失败。

预期溶液:

在执行批处理文件中的任何问题,我应该能够登录,或提示错误。执行批处理文件

代码:

  System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe"); 
      procinfo.UseShellExecute = false; 
      procinfo.RedirectStandardError = true; 
      procinfo.RedirectStandardInput = true; 
      procinfo.RedirectStandardOutput = true; 

      System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo); 

      System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName); 
      System.IO.StreamReader sroutput = process.StandardOutput; 
      System.IO.StreamWriter srinput = process.StandardInput; 

      while (stream.Peek() != -1) 
      { 
       srinput.WriteLine(stream.ReadLine()); 
      } 

      Log.Flow_writeToLogFile("Executed .Bat file : " + LatestFileName); 
      stream.Close(); 
      process.Close(); 
      srinput.Close(); 
      sroutput.Close(); 

非常urgent..Help!

回答

1

我不知道您的问题具体所在,但我已经用下面的代码没有问题:

using (FileStream file = new FileStream("xyz.cmd", FileMode.Create)) { 
    using (StreamWriter sw = new StreamWriter(file)) { 
     sw.Write("@echo ====================\n"); 
     sw.Close(); 
    } 
} 

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.FileName = "xyz.cmd"; 
//p.StartInfo.RedirectStandardOutput = true; 
p.Start(); 
//String s = p.StandardOutput.ReadLine(); 
//while (s != null) { 
// MessageBox.Show(s); 
// s = p.StandardOutput.ReadLine(); 
//} 
p.WaitForExit(); 

显然,这被砍倒了一下隐藏我的“秘密的目的酱“,但这是目前正在使用的生产没有问题的代码。

我确实有一个问题。为什么不直接执行cmd文件而不是运行cmd.exe

可能我要做的第一件事就是打印出BatchPath + LatestFileName的值,看看你是否创建了任何奇怪的命名文件,这会阻止cmd.exe运行它们。

+0

我创建一个.Bat文件并在cmd.exe中执行。在这种情况下,XYZ.cmd是哪里?我在这里错过了什么吗?一旦我写了一个批处理文件,我把它命名为“string.Format(”{0:dd-MM-yyyy [HH-mm-ss-fffff]}“,dt);”使每个批处理文件名称唯一。帮助...谢谢。 – Anuya 2010-09-23 02:51:52

+1

@Anuya,你正在运行'cmd.exe'并将批处理文件的每一行传递给它的标准输入。这似乎是一个复杂的方式来做到这一点。由于批处理文件已经在磁盘上,我只需运行它而不是'cmd.exe',那么您不必担心将单个行发送给它。只需将我的给定代码中的'xyz.cmd'替换为您自己的批处理文件名(基于日期/时间)即可。我的'使用'位就是为了向你展示我是如何创建批处理文件的。实际运行以'Process p = ...'位开始。 – paxdiablo 2010-09-23 03:09:59