2016-06-11 63 views
1

我想一些幫助來獲得聯繫人的縮略圖並將其保存到本地存儲,我順利地拿到了接觸縮略圖,但我不能讓從流實際的形象,這是我的代碼:UWP - 如何將聯繫人縮略圖保存到本地存儲?

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); 

這段代碼在本地存儲中創建一個空的圖像,有幫助嗎?

感謝您的時間

回答

2

這裏的問題是,你錯過了Stream.Flush method刷新緩衝區到底層的流。您可以在fileStream.WriteAsync方法之後添加fileStream.Flush();來解決您的問題。

除此之外,我們還需要撥打Stream.Dispose Method來釋放流在完成使用時所使用的資源。此方法通過將任何更改寫入後備存儲並關閉流釋放資源來處置流。所以我們可以在fileStream.WriteAsync方法之後使用fileStream.Dispose()

一個建議的方式來調用Dispose方法是使用C#使用聲明類似以下內容:

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); 
    } 
} 
+0

大它只是完美的,謝謝 – MohamedMokhtar