Reputation: 53
i want some help to get the thumbnail image of a Contact and save it to Local Storage, i successfully got the contact Thumbnail but i can't get the actual image from the stream, this is my Code:
var contactStore = await ContactManager.RequestStoreAsync();
var contacts = await contactStore.FindContactsAsync();
var myContact = contacts[0]; //I am sure that this Contact has a Thumbnail
var stream = await myContact.Thumbnail.OpenReadAsync();
byte[] buffer = new byte[stream.Size];
var readBuffer = await stream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);
var fileStream = await file.OpenStreamForWriteAsync();
await fileStream.WriteAsync(readBuffer.ToArray(), 0, (int)readBuffer.Length);
this code creates an empty image in the local storage, any help ?
thanks for your time
Upvotes: 1
Views: 575
Reputation: 15758
The problem here is that you missed Stream.Flush
method to flush the buffer to the underlying stream. You can add fileStream.Flush();
after fileStream.WriteAsync
method to fix your issue.
Besides this, we also need to call Stream.Dispose Method to releases the resources used by the Stream when we finish using it. And this method disposes the stream, by writing any changes to the backing store and closing the stream to release resources. So we can just use fileStream.Dispose()
after fileStream.WriteAsync
method.
A recommend way to call the Dispose
method is using the C# using statement like following:
var contactStore = await ContactManager.RequestStoreAsync();
var contacts = await contactStore.FindContactsAsync();
var myContact = contacts[0]; //I am sure that this Contact has a Thumbnail
using (var stream = await myContact.Thumbnail.OpenReadAsync())
{
byte[] buffer = new byte[stream.Size];
var readBuffer = await stream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenStreamForWriteAsync())
{
await fileStream.WriteAsync(readBuffer.ToArray(), 0, (int)readBuffer.Length);
}
}
Upvotes: 2
Reputation: 970
I believe you may have to call stream.Dispose() after you read from it or else initialize the stream with a using directive: using (var outputStream = stream.GetOutputStreamAt(0))
The following link might be useful: https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files?f=255&MSPPError=-2147217396
Upvotes: 2