当构建操作是内容/资源时,相对uri错误不支持此操作

时间:2014-09-19 14:39:46

标签: c# windows-phone isolatedstorage

问题:我想将图像写入隔离存储。我使用下面的代码来获取图像流,并使用可写位图将其写入隔离存储。

我尝试了什么:谷歌搜索后,我实施了以下解决方案

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();
}

这里的问题是,当我尝试通过Application.GetResourceStream获取图像时(显示在上面的注释代码中),结果是:

  

相对uri不支持此操作

我检查了MSDN article,以及这些SO问题(Get stream of local image. Windows phone 8Application.GetResourceStream throws IOException)来验证图片的URI路径,但仍然无法获取{{1} }。

当我将图片的构建操作设置为“嵌入式资源”并尝试使用StreamResourceInfo获取流时,它正常工作(如上面的代码所示)。

如何使用“内容”/“资源”的构建操作来处理图像?在我们的项目中,所有图像大多是“内容”/“资源”。

任何帮助都将受到高度赞赏。非常感谢您的时间和精力。

1 个答案:

答案 0 :(得分:1)

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

对我来说非常适合。图像构建操作设置为Content

确保路径正确