Michael Meyer
Michael Meyer

Reputation: 2184

Porting .NET Library for reuse in UWP App

I am working on a project to reuse one of my old .NET Libraries in an UWP App. I read several articles about the .NET 2.0 Standard Library.

https://learn.microsoft.com/en-us/windows/uwp/porting/desktop-to-uwp-migrate

I followed the steps in that article and created a new .NET Standard 2.0 Library, copied my old source files into the new library project and installed the missing NuGet Packages and compiled the project without any errors.

Next step was to create an UWP app and add the library project as reference.

My Library is transforming files from one format into a different format. So it uses the System.IO and System.Xml.Serialization Namespaces. I know that the security settings for File Reading and Writing were changed in UWP and Windows Store Apps and this causes some problems.

I am opening a file like this

FileOpenPicker fileOpenPicker = new FileOpenPicker();

fileOpenPicker.SuggestedStartLocation = PickerLocationId.Desktop;

fileOpenPicker.FileTypeFilter.Clear();

fileOpenPicker.FileTypeFilter.Add(".txt");

StorageFile file = await fileOpenPicker.PickSingleFileAsync();

// and here I am calling my Library

var doc = ParserFactory.Parse(file.Path);

// and that's what my library is trying to do

....
var myfile = File.OpenRead(filename)

// File.OpenRead throws a Security Exception.

I designed the interface of my library in that way that you have to pass the filepath and the library itself will take care about the rest.

So does someone know a solution to avoid the security exception? I really would appreciate not to rewrite my library and/or to "pollute" my library with the Windows.Storage Namespace.

Thanks in advance

Upvotes: 2

Views: 167

Answers (1)

Laith
Laith

Reputation: 6091

My recommendation is to create an overload for ParserFactory.Parse(Stream stream) and use the StorageFile to open a Stream:

var file = await fileOpenerPicker.PickSingleFileAsync();
var stream = await file.OpenStreamForReadAsync();
var doc = ParserFactory.Parse(stream);

Not sure how your Parse function works, but hopefully all you care about is the Stream implementation, not FileStream.

Upvotes: 2

Related Questions