Home > Blockchain >  c# after copying stream it wont work anymore
c# after copying stream it wont work anymore

Time:12-23

If I did this in my MAUI project:

var uploadImage = new UploadImage();
var img = await uploadImage.OpenMediaPickerAsync();

var imagefile = await uploadImage.Upload(img);
var imageBytes = uploadImage.StringToByteBase64(imagefile.byteBase64);
var stream = uploadImage.ByteArrayToStream(imageBytes);

img_profilePic.Source = ImageSource.FromStream(() => stream); //working

I am displaying an image from my ios simulator. At one point in time I have the stream of the IO at my displosal.

If I now add

MemoryStream newStream = new MemoryStream();
stream.CopyTo(newStream);

these two lines of code to my code above, the image I was displaying at that point dissapears. SO somehow, when I copy my stream, I for some reason also delete the already existing stream...?

What is going on here...

CodePudding user response:

The point of streams is to be able to process very large amounts of data (sequentially) without having to load all that data into memory (at once anyway), which is what happens if instead of streams you work with collections. So, what stream do is track the current position so they can keep loading more data to memory when the position moves forward and unload already processed data. So, using the same stream for two things it's not going to work because the second usage won't get the data that the first usage has already consumed.

That said, it's possible to reset the position of a stream with the seek operation (as long as the type of stream you are using allows it).

Check out this answer https://stackoverflow.com/a/1746108/352826

CodePudding user response:

SO somehow, when I copy my stream, I for some reason also delete the already existing stream...?

It's far more likely that you're trying to use the same stream as multiple sources without rewinding it. Streams have a position that increases as you use it.

In short, use this when you want to reuse your stream:

stream.Position = 0;

Assuming, of course, that whatever stream you're using is rewindable in the first place. If not, then copy it to a memory stream first and reuse that as many times as you wish, rewinding between uses.

  • Related