/// <summary> /// Creates a temporary image file from a download from a URL /// /// If you don't pass a file a temporary file is created in Temp Files folder. /// You're responsible for cleaning up the file after you are done with it. /// /// You should check the filename that is returned regardless of whether you /// passed in a filename - if the file is of a different image type the /// extension may be changed. /// </summary> /// <param name="filename">Url of image to download</param> /// <param name="imageUrl">Optional output image file. Filename may change extension if the image format doesn't match the filename. /// If not passed a temporary files file is created. Caller is responsible for cleaning up this file. /// </param> /// <param name="settings">Optional Http Settings for the request</param> public static async Task <string> DownloadImageToFileAsync(string imageUrl, string filename = null, HttpRequestSettings settings = null) { if (string.IsNullOrEmpty(imageUrl) || !imageUrl.StartsWith("http://") && !imageUrl.StartsWith("https://")) { return(null); } string newFilename; if (string.IsNullOrEmpty(filename)) { filename = Path.Combine(Path.GetTempPath(), "~img-" + DataUtils.GenerateUniqueId()); } filename = Path.ChangeExtension(filename, "bin"); var client = new HttpUtilsWebClient(settings); try { await client.DownloadFileTaskAsync(imageUrl, filename); var ct = client.ResponseHeaders[HttpRequestHeader.ContentType]; var ext = ImageUtils.GetExtensionFromMediaType(ct); if (ext == null) { return(null); // invalid image type } newFilename = Path.ChangeExtension(filename, ext); if (File.Exists(newFilename)) { File.Delete(newFilename); } // rename the file File.Move(filename, newFilename); } catch { if (File.Exists(filename)) { File.Delete(filename); } return(null); } return(newFilename); }