简体   繁体   中英

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. 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);

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

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?

Thanks in advance for your help!

Update

Information in this post is outdated. Please refer for example here .

Original answer

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM