Search code examples
windows-runtimewinrt-async

Read a file in WinRT class library


In a Windows Store app project I was reading a File like this:

var uri = new Uri("ms-appx:///DataModel/Accounts.csv");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

var read = await FileIO.ReadTextAsync(file);

The file Accounts.csv was added with build action content.

I have now moved the code to a separate class library. File is still added with build Action content.

But the uri scheme does not seem to work anymore.

I've also tried:

var file = await StorageFile.GetFileFromPathAsync("/DataModel/Accounts.csv");
var read = await FileIO.ReadTextAsync(file);

How do I access a file in a WinRT class library? Does the file library behave differently than the Store app project?


Solution

  • You can access file in Windows Store class library like this.

    var _Assembly = Assembly.Load(new AssemblyName("ASSEMBLY_NAME"));
    var _Stream = _Assembly.GetManifestResourceStream("YOUR_FILE_NAME_WITH_PATH.xml");
    

    Please note in class library path members are seperated by . not by \

    To get all the resource names

    var names = _Assembly.GetManifestResourceNames();
    

    The GetManifestResourceStream method will always returns NULL if the resource built action property is not set to embedded resource