Write byte array to storage file in windows phone

10,159

Solution 1

To write file to disc try this code:

StorageFile sampleFile = await myfolder.CreateFileAsync(imagename.ToString(), 
   CreateCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sampleFile, ImageArray);

Memory stream creates stream that writes in memory so it is not applicable to this problem.

Solution 2

        StorageFolder folder = ApplicationData.Current.LocalFolder;
        StorageFile imageFile = await folder.CreateFileAsync("Sample.png", CreationCollisionOption.ReplaceExisting);

        using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
            {
                using (DataWriter dataWriter = new DataWriter(outputStream))
                {
                    dataWriter.WriteBytes(imageBuffer);
                    await dataWriter.StoreAsync();
                    dataWriter.DetachStream();

                }
                //await outputStream.FlushAsync();
            }
            //await fileStream.FlushAsync();
        }
Share:
10,159
Arrie
Author by

Arrie

if you can't explain it simple , you don't know it well enough! WPF Jedi, C# Ninja! SOreadytohelp

Updated on June 22, 2022

Comments

  • Arrie
    Arrie about 2 years

    I'm using Visual studio 2012, c#, silverlight, windows phone 8 app.

    We get our data from a webservice, and through the webservice we get a picture that is an base64 string.

    I convert it to a byte array, and now I want to save it so the Storage of the windows phone, using a memory stream? I don't know if it is the right approach. I don't want to save it to isolated storage, just the local folder because I want to show the picture after a person tapped on the link.

    this is what I have so far.

     byte[] ImageArray;
     var image = Attachmentlist.Attachment.ToString();
     imagename = Attachmentlist.FileName.ToString();
     ImageArray = Convert.FromBase64String(image.ToString());
    
     StorageFolder myfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     await myfolder.CreateFileAsync(imagename.ToString());
     StorageFile myfile = await myfolder.GetFileAsync(imagename.ToString());
    
    
     MemoryStream ms = new MemoryStream();
    

    so after I have initialized the memory stream how do I take the byte array and write it to the storage file, and after that retrieve it again?