2012-02-15 191 views
0

我知道我的标题与StackOverflow中的其他人一样,但我的意图是其他。在C#中使用相同的ProcessStartInfo实例执行多个命令(使用BCP)

我创建了一个C#函数,它使用BCP命令为我的数据库中的每个表创建BCP文件。下面的代码是一个示例,是函数的一部分。

List<string> tables = GetTables(); // a function which takes all tables from my database 

string command = @"bcp ADatabase.dbo.{0} out {0}.bcp -n -Usa -Ppassword"; 

ProcessStartInfo processInfo = null; 
    try { 
     foreach (string table in tables) { 
      command = string.Format(command, table); 
      processInfo = new ProcessStartInfo("cmd", "/c " + command); 
      processInfo.RedirectStandardOutput = true; 
      processInfo.CreateNoWindow = false; 
      Process process = new Process(); 
      process.StartInfo = processInfo; 
      process.Start(); 
      string result = process.StandardOutput.ReadToEnd(); 
      Console.WriteLine(result); 
     } 
    } catch (Exception e) { 
     Console.WriteLine(e.Message); 
    } 

我想避免执行多个窗口,我想在同一个窗口中执行每个命令行。

我的代码是好的还是替代?

感谢

回答

2

我不确定是否有办法打开一个命令窗口,然后继续发布命令给它,如果有人有一个聪明的方法做到这一点,这将是很好的。

您可以使用Streamwriter编写一个包含您想要的所有命令的批处理文件,然后运行该批处理文件。那至少只会打开一个进程。

StreamWriter sw = new StreamWriter("MyBatchFile.bat"); 
      string command = @"bcp ADatabase.dbo.{0} out {0}.bcp -n -Usa -%1"; 
      ProcessStartInfo processInfo = null; 
      try 
      { 
       foreach (string table in tables) 
       { 
        command = string.Format(command, table); 
        sw.WriteLine(command);           
       } 
       sw.Flush(); 
       sw.Close(); 
       processInfo = new ProcessStartInfo("cmd", "/c MyBatchFile.Bat Ppassword"); 
       processInfo.RedirectStandardOutput = true; 
       processInfo.CreateNoWindow = false; 
       Process process = new Process(); 
       process.StartInfo = processInfo; 
       process.Start(); 
       string result = process.StandardOutput.ReadToEnd(); 
       Console.WriteLine(result); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 

批处理文件在命令行中的“%1”,所以,当你开始你的程序中通过数据库的密码到批处理文件

ProcessStartInfo("cmd", "/c MyBatchFile.Bat Ppassword"); 

这应该确保,如果任何人都可以找到批处理文件,它只有%1的密码。

不知道这是不是你有什么更好的已经...但它只是打开一个命令行窗口:)

马丁

0

一个非常简单的选择是使用&&运营商建立一个庞大的命令。这里有一个片段来说明这个想法:cmd /c echo hello && echo world。这里的缺点是,如果你的任务失败了,找出哪一个任务有点困难。

您可以随时将命令写入本地* .bat文件,然后处理该文件。然后,如果出现故障,您可以更好地了解故障发生的位置,并且您希望将cmd参数从/c切换到/k,以便您可以保持该窗口处于打开状态以查看发生了什么。