如何访问 .NET Standard 2.0 DLL 中的文件? [英] How to access a file in .NET Standard 2.0 DLL?

查看:29
本文介绍了如何访问 .NET Standard 2.0 DLL 中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的光临.

这是我面临的问题,希望得到一些帮助.

Here is the issue I am facing and would appreciate some help.

我正在尝试访问 .NET 标准 DLL 中的文件.如果我在测试 UWP 应用中使用 Windows.Storage 命名空间,则一切正常,如下所示:

I am trying to access a file in a .NET standard DLL. Everything works if I use the Windows.Storage namespace, in a test UWP app, like so:

Windows.Storage.StorageFile f = await StorageApplicationPermissions.FutureAccessList.GetFileAsync("TestPickedFileToken1");
        txt.Text = await Windows.Storage.FileIO.ReadTextAsync(f);

真正的应用程序是访问 .NETStandard 2.0 DLL 的 MVVM UWP 应用程序(针对 Fall Creators Update).问题是我找不到包含要添加到我的 DLL 的 Windows.Storage 命名空间的程序集.它在 UWP 中可用,当我尝试在 System.IO 中使用以下内容时,它使我可以访问 DLL 中的路径被拒绝错误:

The real app is a MVVM UWP app (targeting Fall Creators Update) that accesses a .NETStandard 2.0 DLL. The problem is that I can't find the assembly that contains Windows.Storage namespace to add to my DLL. It is available in the UWP and when I try to use the following in System.IO it gives me an access to path denied error in the DLL:

string s = File.ReadAllText(filename);

我需要从 DLL 读取/写入文件.如果我在 UWP 应用程序的 ViewModel 中读/写,它将起作用,但我不想这样做.是否可以在我的 DLL 中添加对 Windows.Storage 的引用,或者是否有其他方法来访问 DLL 中的文件?

I need to read/write to the file from the DLL. It will work if I read/write in the ViewModel of the UWP app but I don't want to do that. Is it possible add a reference to Windows.Storage in my DLL or is there an alternative to accessing a file in the DLL?

预先感谢您的帮助!

推荐答案

更新

此帖子中的信息已过时.请参考例如此处.

很遗憾,如果没有 StorageFile API,您将无法访问任何文件路径.当用户使用 FilePicker 授予您对文件的访问权限并且您以 StorageFile 的形式获得引用时,您仍然无法直接使用System.IO 类.

Unfortunately you cannot access any file path without the StorageFile API. When the user grants you access to a file using the FilePicker and you get the reference in form of a StorageFile, you still don't have access to that same path directly using System.IO classes.

同时,您不能在 .NET Standard 库中使用 StorageFile API.但是,您可以做的是从 StorageFile 获取一个 System.IO.Stream,然后您可以在 .NET Standard 库中使用它:

At the same time you cannot use StorageFile APIs in a .NET Standard library. What you can do however is to get a System.IO.Stream from a StorageFile which you can then use in your .NET Standard library:

var readStream = await file.OpenStreamForReadAsync();
var writeStream = await file.OpenStreamForWriteAsync();

要访问此扩展方法,请确保将 using System.IO; 添加到源代码文件的顶部.

To access this extension method, make sure to add using System.IO; to the top of your source code file.

这篇关于如何访问 .NET Standard 2.0 DLL 中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆