本文整理汇总了C#中IFileInfo.ToDataUri方法的典型用法代码示例。如果您正苦于以下问题:C# IFileInfo.ToDataUri方法的具体用法?C# IFileInfo.ToDataUri怎么用?C# IFileInfo.ToDataUri使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IFileInfo
的用法示例。
在下文中一共展示了IFileInfo.ToDataUri方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DownloadImageAndConvertToDataUri
/// <summary>
/// Downloads an image at the provided URL and converts it to a valid Data Uri scheme (https://en.wikipedia.org/wiki/Data_URI_scheme)
/// </summary>
/// <param name="url">The url where the image is located.</param>
/// <param name="logger">A logger.</param>
/// <param name="fallbackFileInfo">A FileInfo to retrieve the local fallback image.</param>
/// <param name="fallbackMediaType">The media type of the fallback image.</param>
/// <param name="messageHandler">An optional message handler.</param>
/// <returns>A string that contains the data uri of the downloaded image, or a default image on any error.</returns>
public static async Task<string> DownloadImageAndConvertToDataUri(this string url, ILogger logger, IFileInfo fallbackFileInfo, string fallbackMediaType = "image/png", HttpMessageHandler messageHandler = null)
{
// exclude completely invalid URLs
if (!string.IsNullOrWhiteSpace(url))
{
try
{
// set a timeout to 10 seconds to avoid waiting on that forever
using (var client = new HttpClient(messageHandler) { Timeout = TimeSpan.FromSeconds(10) })
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
// set the media type and default to JPG if it wasn't provided
string mediaType = response.Content.Headers.ContentType?.MediaType;
mediaType = string.IsNullOrWhiteSpace(mediaType) ? "image/jpeg" : mediaType;
// return the data URI according to the standard
return (await response.Content.ReadAsByteArrayAsync()).ToDataUri(mediaType);
}
}
catch (Exception ex)
{
logger.LogInformation(0, ex, "Error while downloading resource");
}
}
// any error or invalid URLs just return the default data uri
return await fallbackFileInfo.ToDataUri(fallbackMediaType);
}