2017-10-16 56 views
1

我试图采取使用Chrome无头从一个ASP.Net MVC应用程序的截图,下面的代码:以使用Chrome无头和截图C#

public string TakeScreenshot(ScreenshotRequest request) 
{ 
    var pathToScreenshotFile = Path.Combine(Path.GetTempPath(), $"{request.FileName}.png"); 
    var arguments = [email protected]" --headless --hide-scrollbars --disable-gpu --screenshot=""{pathToScreenshotFile}"" --window-size={request.Width},{request.Height} https://google.com"; 

    var psi = new ProcessStartInfo(pathToBrowser) { UseShellExecute = false, Verb = "runas" }; 
    using (Process process = Process.Start(psi)) 
    { 
     Thread.Sleep(1000); 
     var image = string.Empty; 
     var executionCount = 0; 
     while(image == string.Empty && executionCount < 5) 
     { 
      if (File.Exists(pathToScreenshotFile)) 
      { 
       image = Convert.ToBase64String(File.ReadAllBytes(pathToScreenshotFile)); 
      } 
      else 
      { 
       Thread.Sleep(1000); 
      } 
     } 
     return image; 
    } 
} 

pathToBrowser变量指向铬可执行文件: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

出于某种原因,该文件还没有生成,但是如果我打开一个终端,运行以下命令它的工作原理:

E:\sources\chromium\bin\chrome.exe" --headless --hide-scrollbars --disable-gpu --screenshot="C:\Windows\TEMP\5353e1ab-783c-442a-8d72-54d030529e68a.png" --window-size=1920,874 https://google.com 

一有什么想法?我认为它需要作为管理员运行,因此“runas”,但这并没有帮助。

编辑:

我认为这是相关权限的东西,因为当我从控制台应用程序运行在相同的代码工作。现在我有一个包含完全控制给每个人的Chrome的文件夹。我不知道我还错过了什么。

回答

0

它对我很好。我确实必须在ProcessStartInfo中包含arguments

private void Form1_Load(object sender, EventArgs e) 
{ 
    var output = TakeScreenshot(@"C:\Windows\TEMP\5353e1ab-783c-442a-8d72-54d030529e68a.png"); 
} 
public string TakeScreenshot(string request) 
{ 
    var pathToBrowser = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"; 
    var pathToScreenshotFile = Path.Combine(Path.GetTempPath(), $"{request}.png"); 
    var arguments = [email protected]" --headless --hide-scrollbars --disable-gpu --screenshot=""{pathToScreenshotFile}"" --window-size={1920},{874} https://google.com"; 

    var psi = new ProcessStartInfo(pathToBrowser,arguments) { UseShellExecute = false, Verb = "runas" }; 
    using (Process process = Process.Start(psi)) 
    { 
     Thread.Sleep(1000); 
     var image = string.Empty; 
     var executionCount = 0; 
     while (image == string.Empty && executionCount < 5) 
     { 
      if (File.Exists(pathToScreenshotFile)) 
      { 
       image = Convert.ToBase64String(File.ReadAllBytes(pathToScreenshotFile)); 
      } 
      else 
      { 
       Thread.Sleep(1000); 
      } 
     } 
     return image; 
    } 
}