【问题标题】:Getting System.InvalidOperation exception while trying to execute command line script using C#尝试使用 C# 执行命令行脚本时出现 System.InvalidOperation 异常
【发布时间】:2016-12-21 23:24:58
【问题描述】:

我正在尝试使用 phantomjs 执行生成 PDF 文件的命令。

如果我使用命令提示符执行以下命令,一切正常。

C:\phantomjs-2.1.1\bin\phantomjs.exe C:\phantomjs-2.1.1\rasterize.js http://localhost:9992/index.html outputFile.pdf A4 landscape 0.1in

如果我尝试使用 C# 执行相同的操作,我明白了

System.InvalidOperation 异常。

这是我正在使用的代码:

ProcessStartInfo startInfo = new ProcessStartInfo();
var url = "http://localhost:9992/index.html"
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false ; 
startInfo.FileName = "C:\phantomjs-2.1.1\bin\phantomjs.exe";
startInfo.WindowStyle = ProcessWindowStyle.Normal;

startInfo.Arguments = @"/c /K C:\phantomjs-2.1.1\rasterize.js " + url + "C:\temp\output.pdf A4 landscape 0.1in";

try
{
    // Start the process with the info we specified.
    // Call WaitForExit and then the using statement will close.
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch
{
    // Log error.
}

调试时查看下图检查器。

【问题讨论】:

  • 你为什么启动cmd.exe为什么不设置startInfo.FileName = "C:\phantomjs-2.1.1\bin\phantomjs.exe";然后做startInfo.Arguments = @"C:\phantomjs-2.1.1\rasterize.js " + url + " output.pdf A4 landscape 0.1in"
  • 您可能还想记录输出,以便查看发生了什么。查看其他一些流程启动器实现以了解如何做到这一点,例如github.com/cake-build/cake/blob/…
  • 如果您想使用 cmd.exe,请不要忘记在参数前添加 /C,否则 cmd.exe 将在没有任何参数的情况下运行并立即关闭
  • 另外,您的代码显示您的变量名为exeProcess,但您的屏幕截图显示它名为proc,您确定您查看的是正确的对象吗?
  • @ScottChamberlain:我尝试了很多东西,我想我更改了变量名然后我截取了屏幕截图。

标签: c# .net c#-4.0 system.diagnostics invalidoperationexception


【解决方案1】:
ProcessStartInfo startInfo = new ProcessStartInfo();
var url = "http://localhost:9992/index.html"
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false ; // This must be false to use env variable
startInfo.FileName = @"C:\phantomjs-2.1.1\bin\phantomjs.exe";
startInfo.WindowStyle = ProcessWindowStyle.Normal;

startInfo.Arguments = @" C:\phantomjs-2.1.1\rasterize.js " + url + @" C:\phantomjs-2.1.1\output.pdf A4 landscape 0.1in";

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch
{
    // Log error.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2011-06-17
    • 2012-05-22
    相关资源
    最近更新 更多