[英]How to access a file in .NET Standard 2.0 DLL?
Thank you for visiting.谢谢你的拜访。
Here is the issue I am facing and would appreciate some help.这是我面临的问题,希望得到一些帮助。
I am trying to access a file in a .NET standard DLL.我正在尝试访问 .NET 标准 DLL 中的文件。 Everything works if I use the Windows.Storage namespace, in a test UWP app, like so:
如果我在测试 UWP 应用程序中使用 Windows.Storage 命名空间,则一切正常,如下所示:
Windows.Storage.StorageFile f = await StorageApplicationPermissions.FutureAccessList.GetFileAsync("TestPickedFileToken1");
txt.Text = await Windows.Storage.FileIO.ReadTextAsync(f);
The real app is a MVVM UWP app (targeting Fall Creators Update) that accesses a .NETStandard 2.0 DLL.真正的应用程序是访问 .NETStandard 2.0 DLL 的 MVVM UWP 应用程序(针对 Fall Creators Update)。 The problem is that I can't find the assembly that contains Windows.Storage namespace to add to my DLL.
问题是我找不到包含要添加到我的 DLL 的 Windows.Storage 命名空间的程序集。 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:
它在 UWP 中可用,当我尝试在 System.IO 中使用以下内容时,它使我可以访问 DLL 中的路径被拒绝错误:
string s = File.ReadAllText(filename);
I need to read/write to the file from the DLL.我需要从 DLL 读取/写入文件。 It will work if I read/write in the ViewModel of the UWP app but I don't want to do that.
如果我在 UWP 应用程序的 ViewModel 中读/写,它将起作用,但我不想这样做。 Is it possible add a reference to Windows.Storage in my DLL or is there an alternative to accessing a file in the DLL?
是否可以在我的 DLL 中添加对 Windows.Storage 的引用,或者是否有访问 DLL 中文件的替代方法?
Thanks in advance for your help!在此先感谢您的帮助!
Information in this post is outdated.此帖子中的信息已过时。 Please refer for example here .
请参考这里的例子。
Unfortunately you cannot access any file path without the StorageFile
API.不幸的是,如果没有
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.当用户使用
FilePicker
授予您对文件的访问权限并且您以StorageFile
形式获得引用时,您仍然无法直接使用System.IO
类访问同一路径。
At the same time you cannot use StorageFile
APIs in a .NET Standard library.同时,您不能在 .NET Standard 库中使用
StorageFile
API。 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:但是,您可以做的是从
StorageFile
获取System.IO.Stream
,然后您可以在 .NET Standard 库中使用它:
var readStream = await file.OpenStreamForReadAsync();
var writeStream = await file.OpenStreamForWriteAsync();
To access this extension method, make sure to add using System.IO;
要访问此扩展方法,请确保
using System.IO;
添加using System.IO;
to the top of your source code file.到源代码文件的顶部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.