使用参数启动命令提示符

时间:2017-09-15 18:52:10

标签: c#

我需要使用WPF C#应用程序中的参数从提示符启动命令,以同步两个数据库。

file.bat中的命令如下:

"c:\Program Files\Microsoft SQL Server\100\COM\replmerg.exe" -Publisher [sql2008-srv\sql2008srv] -PublisherDB [MIODB] -Publication [DBPublication] -Subscriber [UTENTE\SQL2008R2EXP] -SubscriberDB [MIODB] -SubscriptionType 1 -SubscriberSecurityMode 1 -Distributor [sql2008-srv\sql2008srv] -OutputVerboseLevel 4 -Output C:\Windows\Temp\mergeagent.log 

在我的代码下面,但没有运行。只需用闪烁的光标打开shell:

string ciao = "\"c:\\Program Files\\Microsoft SQL Server\\100\\COM\\replmerg.exe\" -Publisher [sql2008-srv\\sql2008srv] -PublisherDB [DataNavi] -Publication [DataNaviPublication] -Subscriber [SFRANCESCO\\SQL2008R2EXP] -SubscriberDB [DataNavi] -SubscriptionType 1 -SubscriberSecurityMode 1 -Distributor [sql2008-srv\\sql2008srv] -OutputVerboseLevel 4 -Output C:\\Windows\\Temp\\mergeagent.log ";

try
{
    Process.Start("CMD.exe", "/K" +ciao);
}
catch (Exception ex)    
{        
    // Implement appropriate error handling here.
    MessageBox.Show("errore:" + ex.Message, "Errore sincronizzazione");
}

1 个答案:

答案 0 :(得分:2)

处理此问题的方法很少

<强> 1。使用cmd.exe / C命令而不是/ K选项。

摘自cmd.exe /?帮助

  

/ C执行字符串指定的命令,然后终止
  / K执行字符串指定的命令,但仍为

string ciao = @"""c:\Program Files\Microsoft SQL Server\100\COM\replmerg.exe"" "+
    @"-Publisher [sql2008-srv\sql2008srv] -PublisherDB [DataNavi] -Publication [DataNaviPublication] "+
    @"-Subscriber [SFRANCESCO\SQL2008R2EXP] -SubscriberDB [DataNavi] -SubscriptionType 1 "+
    @"-SubscriberSecurityMode 1 -Distributor [sql2008-srv\sql2008srv] -OutputVerboseLevel 4 "+
    @"-Output C:\Windows\Temp\mergeagent.log";

try {
    var proc = Process.Start("CMD.exe", "/c " + ciao);
    proc.WaitForExit(); // optionally wait for exit
} catch (Exception ex) {
    // Implement appropriate error handling here.
    Console.WriteLine("error:" + ex.Message);
}

<强> 2。使用批处理文件

有了这么长的参数列表,你可能会遇到引号问题(如果不是现在,那么将来)。更好的方法是让命令保留在批处理文件中并执行批处理文件。

  

输入file.bat
  “c:\ Program Files \ Microsoft SQL Server \ 100 \ COM \ replmerg.exe”-Publisher [sql2008-srv \ sql2008srv] -PublisherDB [MIODB] -Publication [DBPublication] -Subscriber [UTENTE \ SQL2008R2EXP] -SubscriberDB [MIODB] -SubscriptionType 1 -SubscriberSecurityMode 1 -Distributor [sql2008-srv \ sql2008srv] -OutputVerboseLevel 4 -Output C:\ Windows \ Temp \ mergeagent.log

var proc = Process.Start("file.bat");

第3。直接运行命令而不使用cmd.exe

string ciao = @"-Publisher [sql2008-srv\sql2008srv] -PublisherDB [DataNavi] -Publication [DataNaviPublication] " +
    @"-Subscriber [SFRANCESCO\SQL2008R2EXP] -SubscriberDB [DataNavi] -SubscriptionType 1 " +
    @"-SubscriberSecurityMode 1 -Distributor [sql2008-srv\sql2008srv] -OutputVerboseLevel 4 " +
    @"-Output C:\Windows\Temp\mergeagent.log";

var proc = Process.Start(@"c:\Program Files\Microsoft SQL Server\100\COM\replmerg.exe", ciao);