如何从WCF库C#调用cmd命令

时间:2016-05-03 13:06:04

标签: c# wcf

我有一个C#WCF库,我想从WCF库中的一个方法调用cmd命令,但是当我运行代码并调用该方法时,它既不执行cmd命令也不生成任何类型的异常,我应该这样做,我的代码是如此......请有人指导我。

我已经在cmd上验证了该命令,它从cmd成功执行,但不是从WCF库执行,因此命令语法没有任何问题。 在这里输入代码

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
Info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
Info.FileName = "cmd.exe";
Info.Arguments= 
         "\"" + tallyPath + "\"" + "  " 
         + "/TDL:" + tdlPath + " " + "/LOAD:" 
         + cmpCode + "  " + "/SETVAR:SVVarUN:" 
         + uname + " " + "/SETVAR:SVVarPass:"
         + pwd;

proc.StartInfo = startInfo
proc.Start();

2 个答案:

答案 0 :(得分:0)

编辑回答 - 我已经构建了最简单的WCF服务,以尽可能地尝试和模仿您的场景。我测试了这个,它工作正常(粘贴在下面)。请注意上面示例中看起来不正确的注释掉的行。您的StartInfo也存在问题 - 您创建的是"信息"但设置" proc.StartInfo = startInfo"这似乎不存在 - 它应该设置为" Info"。

using System.Diagnostics;
using System.ServiceModel;

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string RunTally();
    }

    public class Service1 : IService1
    {
        public string RunTally()
        {
            var tallyPath = "C:\\temp\\";
            var tallyExe = "tally.exe";
            var cmpCode = "myCmpCode";
            var uname = "myUname";
            var pwd = "myPwd";
            var tdlPath = "myTdlPath";

            Process proc = new Process();
            ProcessStartInfo info = new ProcessStartInfo();
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.RedirectStandardOutput = true;
            info.RedirectStandardInput = true;
            info.RedirectStandardError = true;
            info.UseShellExecute = false;
            info.Arguments =
                // "\"" + tallyPath + "\"" + "  "
                 // +
                 "/TDL:" + tdlPath + " " + "/LOAD:"
                 + cmpCode + "  " + "/SETVAR:SVVarUN:"
                 + uname + " " + "/SETVAR:SVVarPass:"
                 + pwd;
            info.FileName = tallyPath + tallyExe;

            proc.StartInfo = info;            
            proc.Start();

            var textReceived = "";
            while (!proc.StandardOutput.EndOfStream)
            {
                textReceived += proc.StandardOutput.ReadLine();
            }

            return string.Format("The call returned: " + textReceived);
        }
    }
}

答案 1 :(得分:0)

我在某些服务器上遇到此问题,原因是2个问题 1.安全权限有时会阻止命令行exe并要求确认对话框,这是不可见的。 2.使用以下设置解决了另一个问题:

process.StartInfo.UseShellExecute = false;
     process.StartInfo.RedirectStandardOutput = true;
     process.StartInfo.RedirectStandardError = true;
     process.StartInfo.RedirectStandardInput = true;