Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have been trying to get the image from a url then writing the image to disk with no success.
Can anyone help with this?

Example URL is:
https://static.tvmaze.com/uploads/images/medium_portrait/244/610854.jpg

Current code is:

try
			{
				using var client = new HttpClient();
				var getStream = client.GetStreamAsync(webURL);
				using var fileStream = new FileStream(imagePath,FileMode.Create,FileAccess.Write);
				return true;
			}


It always writes out an empty jpg image.
However, when I execute the URL directly it shows e the image.

What I have tried:

I have tried using a retrieval as I do for Json data. But that does not work.
Posted
Comments
Dave Kreskowiak 8-Jan-24 23:57pm    
Hint: You're not reading the bytes from the stream you got back, nor are you writing anything to the fileStream you created, so yeah, the file is going to be empty.

Here's how I do it:
WebClient wc = new WebClient();
outPath = Path.Combine(KnownFolders.Downloads.Path, $"{imageFileName}.{imageFileExtension}");
wc.DownloadFile(imageUrl, outPath);
 
Share this answer
 
Comments
Leonard Salamacha 2023 9-Jan-24 2:41am    
I thought that we are now supposed to use webClient anymore. But to use HttpClient. Thankyou for your input. However, I am looking for a solution using HttpClient.
Just spitballing, but something like this should be possible.
C#
private HttpClient httpClient;
public async Task DownloadImageAndSaveAsync(string sourceFile, string outputFolder, string outputFileName)
{
  try
  {
    using Stream fileStream = await httpClient.GetStreamAsync(fileUrl);
    Directory.CreateDirectory(outputFolder);
    string path = Path.Combine(outputFolder, outputFileName);
    using FileStream outputFileStream = new FileStream(path, FileMode.CreateNew);
    await fileStream.CopyToAsync(outputFileStream);
  }
  catch (Exception ex)
  {
    // If you can do some exception handling, do it here...
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900