GetStreamAsync() Stream Always Null [Answered]

I'm getting a URI from json on my computer and trying to download an image from it. Everything works up to actually putting something in requestBodyStream. It is forever null.
public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small);
var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");

await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small);
var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");

await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
The next debug Step Into would be to get the URI, which it shows by going to the model. Then it seems like it skips the next three lines of code and goes to the second object in the foreach loop. Pressing Step Into again on the last item in the list of cards finishes the program. Nothing is ever downloaded.
75 Replies
canton7
canton72y ago
Are you debugging a release build, by any chance?
BigggMoustache
Probably not, because I don't even know what that means lol.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Korbah
Korbah2y ago
I might use a try/catch to see if you're getting any errors on the lines where it skips to the next item I don't think that's what should happen if an exception is thrown, but I have had similar weird things happen before with async exceptions behaving strangely (Though I didn't think this would happen as long as your return type is Task)
ero
ero2y ago
that code works fine on my end (same url) what you should seriously consider is putting using in front of many of those
using var client = new HttpClient();

using var requestBodyStream = await client.GetStreamAsync(url);
using var fileStream = File.Create(path);

await requestBodyStream.CopyToAsync(fileStream);
using var client = new HttpClient();

using var requestBodyStream = await client.GetStreamAsync(url);
using var fileStream = File.Create(path);

await requestBodyStream.CopyToAsync(fileStream);
this is all i did
BigggMoustache
They just get skipped. Breakpoint only triggers when creating the stream variable (inside the foreach loop)
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
BigggMoustache
Idk what that is but I'll Google it when I'm free later today
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
BigggMoustache
I really appreciate that advice. I'll try it in a few hours when free. I imagine my method is a task, but I'm noob and maybe I forgot. I'll check.
BigggMoustache
public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small.ToString());
Debug.Assert(requestBodyStream != null);

var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");
await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small.ToString());
Debug.Assert(requestBodyStream != null);

var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");
await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
It's like there's no lines after the first var requestBodyStream line. Just skips it all completely. :[
namespace MTGCardDownloader
{
public class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main()
{
string thing = Console.ReadLine();
if (thing == "local") LocalCard();
/* if (thing == "api") await ProcessRepositories();*/

}

private static async Task ProcessRepositories()
{
//Takes Json straight to model, but doesn't let you see json text'
//var cardJson = await client.GetFromJsonAsync<Card>("https://api.magicthegathering.io/v1/cards?name=avacyn");

var jsonHolder = client.GetStringAsync("https://api.magicthegathering.io/v1/cards?name=avacyn");
var msg = await jsonHolder;
var cards = JsonSerializer.Deserialize<Card>(msg);
}

public static async Task LocalCard()
{
string fileName = @"C:\Users\samue\source\repos\Goofin" +
@"\MTGCardDownloader\MTGCardDownloader\MTGCardDownloader\Json\LibrarySample.Json";
string jsonString = File.ReadAllText(fileName);
var cards = JsonSerializer.Deserialize<List<Card>>(jsonString);
await DownloadFunction(cards);

}

public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
using var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small.ToString());
Debug.Assert(requestBodyStream != null);

using var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");
await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
}
}
namespace MTGCardDownloader
{
public class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main()
{
string thing = Console.ReadLine();
if (thing == "local") LocalCard();
/* if (thing == "api") await ProcessRepositories();*/

}

private static async Task ProcessRepositories()
{
//Takes Json straight to model, but doesn't let you see json text'
//var cardJson = await client.GetFromJsonAsync<Card>("https://api.magicthegathering.io/v1/cards?name=avacyn");

var jsonHolder = client.GetStringAsync("https://api.magicthegathering.io/v1/cards?name=avacyn");
var msg = await jsonHolder;
var cards = JsonSerializer.Deserialize<Card>(msg);
}

public static async Task LocalCard()
{
string fileName = @"C:\Users\samue\source\repos\Goofin" +
@"\MTGCardDownloader\MTGCardDownloader\MTGCardDownloader\Json\LibrarySample.Json";
string jsonString = File.ReadAllText(fileName);
var cards = JsonSerializer.Deserialize<List<Card>>(jsonString);
await DownloadFunction(cards);

}

public static async Task DownloadFunction(List<Card> cards)
{
foreach(Card card in cards)
{
using var requestBodyStream = await client.GetStreamAsync(card.ImageUris.Small.ToString());
Debug.Assert(requestBodyStream != null);

using var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg");
await requestBodyStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
}
}
Here's the whole thing. I hope this helps someone see what I did wrong.
ero
ero2y ago
what's the Card class look like? what's in your LibrarySample.Json? can't really do anything without those
BigggMoustache
sure I'll copy em all to $code
MODiX
MODiX2y ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat If your code is too long, post it to: https://paste.mod.gg/
BigggMoustache
I was just hoping there was something obviously wrong with a Task or await or something
ero
ero2y ago
only thing i could see being a bit problematic is how often you do IO (creating a lot of files in a short amount of time) but i don't think that should break the program in any way what .net version are you on?
BigggMoustache
how do I tell? I could have googled that my b
ero
ero2y ago
right click the project > properties
BigggMoustache
net 6
BigggMoustache
just making sure I read the right thing
ero
ero2y ago
👍
BigggMoustache
BlazeBin - zblyqyosyava
A tool for sharing your source code with the world!
BigggMoustache
BlazeBin - xdlkvejdugqt
A tool for sharing your source code with the world!
BigggMoustache
BlazeBin - zdkgmmnsbojo
A tool for sharing your source code with the world!
BigggMoustache
that's the three files in the project
ero
ero2y ago
you have multiple tabs in a single paste
BigggMoustache
i wasn't sure how it worked tbh actually I'm not sure what you meant sorry
ero
ero2y ago
the reason i asked about the .net version is because you don't really use block-scoped namespaces, or the explicit Program class declaration in .net 6 anymore
ero
ero2y ago
ero
ero2y ago
when you click the + here, you can paste multiple files
BigggMoustache
OHHH. I was wondering about the sets lol I also couldn't figure out how to name them lol
ero
ero2y ago
i don't think you can rename them once they exist i just always delete the initial newfile.cs and create a new one so i can name it
BigggMoustache
BlazeBin - wtaoeebjayoe
A tool for sharing your source code with the world!
BigggMoustache
yeah had to delete the default and create new to actually name. I fixed it now. I also spaced and deleted the other ones lol. sorry
ero
ero2y ago
does your code ever even get into the function?
BigggMoustache
It performs the first line of the foreach that's it
ero
ero2y ago
that's genuinely surprising since you're not awaiting LocalCard()
BigggMoustache
well it steps into that first line, looks at the Card.cs model (highlighting Get) and then just repeats that for the two cards in the sampleLibrary
ero
ero2y ago
are you ignoring a bunch of warnings and messages or did you turn them off deliberately
BigggMoustache
warnings yes
ero
ero2y ago
cause you're missing a lot of null checks
BigggMoustache
👀
ero
ero2y ago
nah the json ones are fine to ignore i'd just slap #nullable disable at the start of that file
BigggMoustache
I added await to the LocalCard thing and it did this
ero
ero2y ago
now it's actually executing the code :p
BigggMoustache
well like i said it'd hit breakpoint on first line of foreach before
ero
ero2y ago
which makes absolutely no sense actually
BigggMoustache
lol
ero
ero2y ago
did you turn off a warning for that too?
BigggMoustache
nope
ero
ero2y ago
it should have said "LocalCard is not awaited"
BigggMoustache
maybe I did and don't remember
ero
ero2y ago
ah yeah nevermind, it does execute the code
BigggMoustache
but i doubt it
ero
ero2y ago
but the program finishes before it method does because you don't await
BigggMoustache
that's what i was figuring cool
ero
ero2y ago
BigggMoustache
okay I need to google this await thing and read more. Now I'm curious though why I got the file not found error
ero
ero2y ago
part of the path
BigggMoustache
var fileStream = File.Create($@"C:\Users\samue\Desktop\MTGImage\{card.Name}.jpg"); Doesn't this create the file for the filestream to dump data in?
ero
ero2y ago
any one of the directories are missing i assume you don't have an MTGImage folder on your desktop
BigggMoustache
I do lol I copied the path to ensure it was correct.
ero
ero2y ago
works fine for me with an existing directory consider switching away from var, consider making that httpclient local (with using)
ero
ero2y ago
look again
BigggMoustache
holy fuck That must have been from a frustration deleting and not realizing when remaking ffs alright now to learn when I should use await lol. dude tyvm so I just await everything internet related? lol
ero
ero2y ago
no no, await isn't related to anything web
BigggMoustache
oh lol my only reference to await and task is internet stuff so that was why the assumption
ero
ero2y ago
i can't really explain async development, i'm not that good at it either
BigggMoustache
no worries bud. You saved the day here, thank you and sorry for sperging out at you the other day It was my bad to respond that way
Korbah
Korbah2y ago
You typically await all async functions or functions which return a Task. There is a bit more finesse to it, but you usually want them to complete before your next line(s) of code executes. But yeah, that's what was happening - you were getting an exception in your code, but since you weren't awaiting your function, the debugger does not catch the exception since it does not propagate up. It'll look like the function just stopped working at some point
Accord
Accord2y ago
✅ This post has been marked as answered!
BigggMoustache
tyvm for explanation.