Search code examples
windows-phone-8storagefile

Saving image as StorageFile


I am trying to save an image selected with FileOpenPicker. I am lunching this event when an image is selected

 async void  photoChooserTask_Completed(object sender, PhotoResult e)
{       
// get the file stream and file name           
                Stream photoStream = e.ChosenPhoto;    
                string fileName = Path.GetFileName(e.OriginalFileName);

  // persist data into isolated storage      
    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);    
    using (Stream current = await file.OpenStreamForWriteAsync())    
    {     
        await photoStream.CopyToAsync(current);         
    }      
}         

But this code which will give me the lenght of the saved file return 0

var properties = await file.GetBasicPropertiesAsync();
                i = properties.Size;

Have I done something wrong in saving the image?


Solution

  • You may need to flush the stream.

    If that does not work, add a breakpoint and check the two streams' lengths after the copy. Are they equal? They should be. Anything suspicious on those two stream objects?

    Edit

    On the image you posted, I can see that you use the SetSource method of a BitmapImage with the same Stream that you copy. Once you do that, the Stream's Position will be at the end, as it was just read by that call.

    CopyToAsync copies everything after the current Position of the Stream you call it on. Since the position is at the end, because it was just read, the CopyToAsync does not copy anthing.

    All you need to do to fix your problem is set the stream's Position to 0.