我正在使用Microsoft从Azure获取用户配置文件映像。
见示例:
我正在使用这个API调用使用C#控制台应用程序。我有下面的代码。
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
中是类似的。
当我试图使用以下代码将此映像保存在本地驱动器上时:
System.IO.File.WriteAllBytes(@"C:\image.bmp", Convert.FromBase64String(test.Result));
它给了我错误:
{System.FormatException:输入不是一个有效的Base-64字符串,因为它包含一个非基本的64个字符、两个以上的填充字符或填充字符中的一个非法字符。在System.Convert.FromBase64_ComputeResultLength(Char* inputPtr,Int32 inputLength)在System.Convert.FromBase64CharPtr(Char* inputPtr,Int32 inputLength)在System.Convert.FromBase64String(String s) at Microsoft_Graph_Mail_Console_App.MailClient.d__c.MoveNext() in d:\Source\MailClient.cs:line 125}
我理解这个错误,因为结果不能转换为byte[]。
因此,我想知道,我是否可以直接使用Result
属性中的数据在本地系统上创建和保存映像?
发布于 2017-05-26 05:26:57
对于图像,响应的内容是字节流,而不是字符串。因此,您只需读取响应蒸汽并将其复制到输出流。例如:
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)
而不是它的异步耦合器部分。
https://stackoverflow.com/questions/44202149
复制