从 UWP 访问作为资源嵌入在网络标准 2.0 类库中的存储文件



从UWP如何访问作为资源嵌入在.Net Standard 2类库中的文件?问题如何从 UWP 访问网络标准 2.0 类库中的内容将返回一个流。我们如何返回存储文件?

该文件位于名为"共享"的 .Net 标准 2 项目中,该项目与 UWP 项目位于同一解决方案中。该文件位于共享/报表中,并设置为复制到作为嵌入资源输出。

我试过了

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 格式?

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

还行。我在上面评论中提到的链接只是一个类似的问题。我的目的是告诉您将流保存到存储文件中。但你似乎对它并不熟悉。

我制作了一个代码示例供您参考。

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

最新更新