Search code examples
c#windows-phoneisolatedstorage

This operation is not supported for a relative uri error when build action is Content/Resource


Problem: I want to write images to isolated storage. I am using the below code to get the stream for image and write that using writable bitmap to isolated storage.

What have I tried: After googling, I implemented the below solution

String myImage = "myImage.png";

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

    IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(myImage, FileMode.Create, myIsolatedStorage);

    //Uri uri = new Uri("/myApplication;component/Images/AppIcons/" + myImage, UriKind.Relative);
    //StreamResourceInfo sri = Application.GetResourceStream(uri); // Trying to get image whose Build action is set to 'Resource'

    //Uri uri1 = new Uri("Images/AppIcons/White.png", UriKind.Relative); // Content
    //StreamResourceInfo sri1 = Application.GetResourceStream(uri1); // Trying to get image whose Build action is set to 'Content'

    string[] names = this.GetType().Assembly.GetManifestResourceNames();
    string name = names.Where(n => n.EndsWith(myImage)).FirstOrDefault();
    if (name != null)
    {
        // Trying to get image whose Build action is set to 'Embedded Resource'
        Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);

        if (resourceStream != null)
        {
            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(resourceStream);
            WriteableBitmap wb = new WriteableBitmap(bitmap);

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

    fileStream.Close();
}

The problem here is that when I try to get the image by Application.GetResourceStream (shown in commented code above), then the result is:

this operation is not supported for a relative uri

I checked MSDN article, and a these SO questions (Get stream of local image. Windows phone 8 and Application.GetResourceStream throws IOException) to verify the URI path for images, but it is still not able to get the StreamResourceInfo.

When I set the build action of images to 'Embedded Resource' and try to get stream using GetManifestResourceStream, then it is working properly (Shown in the code above).

How can I make it to work with images with build action of 'Content'/'Resource'? In our project, all images are mostly 'Content'/'Resource'.

Any help will be highly appreciated. Thanks much for your time and effort.


Solution

  • StreamResourceInfo sri1 = Application.GetResourceStream(new Uri("image.png", UriKind.Relative));
    

    works perfect for me. Image build action is set to Content.

    Ensure that path is correct