尝试使用C#执行命令行脚本时获取System.InvalidOperation异常

时间:2016-08-15 18:04:40

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

我正在尝试使用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.
}

调试时请查看以下图片以查看检查器。

enter image description here

1 个答案:

答案 0 :(得分:0)

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.
}