Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write byte array to storage file in windows phone

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?

like image 447
Arrie Avatar asked Jun 03 '13 07:06

Arrie


2 Answers

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.

like image 198
Rafal Avatar answered Nov 16 '22 02:11

Rafal


        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();
        }
like image 6
Shefali Avatar answered Nov 16 '22 01:11

Shefali