2017-05-26 181 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。