2017-10-16 114 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; 
    } 
}