从UWP访问作为Net Standard 2.0类库中的资源嵌入的StorageFile

时间:2018-03-22 08:35:58

标签: c# uwp .net-standard .net-standard-2.0

从UWP我们如何访问作为.Net Standard 2类库中的资源嵌入的文件?问题How to access content from a Net Standard 2.0 class libary from UWP返回一个流。我们如何返回StorageFile?

该文件位于名为Shared的.Net Standard 2项目中,该项目与UWP项目位于同一解决方案中。该文件位于Shared / Reports中,并设置为复制以作为EmbeddedResource输出。

我已经尝试了

Uri resourcePath = new Uri("ms-appx:///Shared/Reports/MyReport");
StorageFile myFile = await StorageFile.GetFileFromApplicationUriAsync(resourcePath);

Uri resourcePath = new Uri("Shared/Reports/MyReport");
StorageFile myFile = await StorageFile.GetFileFromApplicationUriAsync(resourcePath);

两者都返回FileNotFoundException

StorageFile.GetFileFromApplicationUriAsync是否适用?如果是这样,我如何正确格式化URI?

1 个答案:

答案 0 :(得分:1)

  

是,但给定A:的示例不起作用,B:使用特定于pdfiles的方法。

没关系。我在上面的评论中提到的链接只是一个类似的问题。我的目的是告诉你将流保存到StorageFile中。但似乎你并不熟悉它。

我已经提供了一个代码示例供您参考。

public class Class1
{
    /// <summary>
    /// This is the method in my .Net Standard library
    /// </summary>
    /// <returns></returns>
    public static Stream GetImage()
    {
        var assembly = typeof(Class1).GetTypeInfo().Assembly;
        Stream stream = assembly.GetManifestResourceStream("ClassLibrary1.Assets.dog.jpg");
        return stream;
    }
}
    /// <summary>
    /// This method is used to create a StorageFile and save the stream into it, then return this StorageFile
    /// </summary>
    /// <returns></returns>
    private async Task<StorageFile> GetFile()
    {
        StorageFile storageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("Temp.jpg",CreationCollisionOption.ReplaceExisting);
        using (var Srcstream = ClassLibrary1.Class1.GetImage())
        {
            using (var targetStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var reader = new DataReader(Srcstream.AsInputStream()))
                {
                    var outpustream = targetStream.GetOutputStreamAt(0);
                    await reader.LoadAsync((uint)Srcstream.Length);
                    while (reader.UnconsumedBufferLength >0)
                    {
                        uint datatoend = reader.UnconsumedBufferLength > 128 ? 128 : reader.UnconsumedBufferLength;
                        IBuffer buffer = reader.ReadBuffer(datatoend);
                        await outpustream.WriteAsync(buffer);
                    }
                    await outpustream.FlushAsync();
                }
            }
        }
        return storageFile;
    }