Nikola Sivkov
Nikola Sivkov

Reputation: 2852

Save image to isolated storage from BG task

I'm trying to save an image from the web to the isolated storage from a background task but it throws

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll

i'm using this piece of code

 using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(tempJPEG))
            {
                myIsolatedStorage.DeleteFile(tempJPEG);
            }

            IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);

            StreamResourceInfo sri = null;
            Uri uri = new Uri(tempJPEG, UriKind.Relative);
            sri = Application.GetResourceStream(uri);

            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(e.Result);
            WriteableBitmap wb = new WriteableBitmap(bitmap);

            // Encode WriteableBitmap object to a JPEG stream.
            Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);

            //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            fileStream.Close();
        }

This works 100% when it's runing from the app , but not from the background task. Any tips on how to save the image ?

Upvotes: 2

Views: 2283

Answers (1)

JustinAngel
JustinAngel

Reputation: 16102

You need to invoke this code Dispatcher.BeginInvoke() since WriteableBitmap needs to execute on the UI thread and not a background thread. See @ http://codeblog.vurdalakov.net/2012/02/solution-wp7-unauthorizedaccessexceptio.html

Upvotes: 3

Related Questions