2017-05-26 177 views
0

我正在使用Microsoft Graph API從Azure Active Directory獲取用戶配置文件映像。如何將「ContentType = {image/jpeg}」的響應保存爲圖像C#?

見例如:

enter image description here

我利用使用C#控制檯應用程序,該API調用。我有以下代碼。

var httpClient = new HttpClient(); 
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer","MY ACCESS TOKEN"); 
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value"); 
var test = response.Content.ReadAsStringAsync(); 

現在,這裏的響應的內容類型是{image/jpeg}

我收到的數據看起來像在屬性Result從以下圖像。

enter image description here

當我嘗試使用下面的代碼保存在我的本地驅動器上的這一形象:

System.IO.File.WriteAllBytes(@"C:\image.bmp", Convert.FromBase64String(test.Result)); 

它給我的錯誤:

{System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. at System.Convert.FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) at System.Convert.FromBase64String(String s)
at Microsoft_Graph_Mail_Console_App.MailClient.d__c.MoveNext() in d:\Source\MailClient.cs:line 125}

我明白了這個錯誤,因爲結果不能轉換爲字節[]

所以,我想知道,我可以直接使用Result屬性中的數據在我的本地系統上創建和保存圖像嗎?

回答

2

在圖像的情況下,響應的內容是字節流而不是字符串。 因此,您只需讀取響應流並將其複製到輸出流。例如:

HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value"); 
using (Stream responseStream = await response.Content.ReadAsStreamAsync()) 
{ 
    using (FileStream fs = new FileStream(@"c:\image.jpg", FileMode.Create)) 
    { 
     // in dotnet 4.5 
     await source.CopyToAsync(fs); 
    } 
} 

如果你是,在dotnet 4.0,使用source.CopyTo(fs)而不是它的異步couterpart。