Search code examples
c#webassemblyuno-platform

How to get a file's content of UNO shared project as string


In regular C#/UWP it is possible without any (bigger) problems to read a file's (or resource's) content to a string variable. How is this done with the UNO platform's WebAssembly build target?

What I already tried: According to the browser's debugging console, my code execution stops (without any exception thrown) as soon as I try to use reflection, for example. Before digging deeper in the JavaScript jungle, I decided to ask the specialists here. (As a last workaround, I thought about using the HTTP client implementation, but I will do this only if there really is no usable alternative.)


Solution

  • The WebAssembly target for Uno does not support reading content files for now as part of the System.IO.File api (and probably won't in the near future because of its synchronous API).

    The easiest way, which works cross platforms, is to use embedded resources:

    <ItemGroup>
      <EmbeddedResource Include="myfile.txt" />
    </ItemGroup>
    

    Then in the code, use something like this:

    static string ReadResource(string fileName)
    {
        var assembly = typeof(Program).Assembly;
        var resourceName = assembly.GetManifestResourceNames()
            .FirstOrDefault(f => f.Contains(fileName));
    
        if (!string.IsNullOrEmpty(resourceName))
        {
            using (var s = new StreamReader(assembly .GetManifestResourceStream(resourceName)))
            {
                return s.ReadToEnd();
            }
        }
        else
        {
            throw new InvalidOperationException(
                $"Unable to find resource {fileName} in {typeof(Program).Assembly}");
        }
    }