Using files in a ASP.NET Core nuget package

To use static (html) files in a NUGET ASP.NET Core package to be displayed I have used the following solution

1. Put the files in a folder ( in my case,blocklyAutomation )

2. Put in the .csproj to embed the files

<ItemGroup>
   <EmbeddedResource Include=”BlocklyAutomation\**\*”>
     <CopyToOutputDirectory>Never</CopyToOutputDirectory>
   </EmbeddedResource>
</ItemGroup>

3.  Create an extension to use it

;

public static void UseBlocklyUI(this IApplicationBuilder appBuilder)
{
    var manifestEmbeddedProvider =
            new ManifestEmbeddedFileProvider(Assembly.GetExecutingAssembly());
    var service = appBuilder.ApplicationServices;
    mapFile(&quot;blocklyAutomation&quot;,manifestEmbeddedProvider,appBuilder);


}

private static void mapFile(string dirName,IFileProvider provider,IApplicationBuilder appBuilder)
{
    var folder = provider.GetDirectoryContents(dirName);
    foreach (var item in folder)
    {
        if (item.IsDirectory)
        {
            mapFile(dirName + &quot;/&quot; + item.Name,provider,appBuilder);
            continue;
        }
        string map = (dirName + &quot;/&quot; + item.Name).Substring(dirName.Length);
        appBuilder.Map(map,app =&gt;
        {
            var f = item;

            app.Run(async cnt =&gt;
            {
                //TODO: find from extension
                //cnt.Response.ContentType = &quot;text/html&quot;;
                using var stream = new MemoryStream();
                using var cs = f.CreateReadStream();
                byte[] buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                while ((bytesRead = cs.Read(buffer,0,buffer.Length)) &gt; 0)
                {
                    stream.Write(buffer,0,bytesRead);
                }
                byte[] result = stream.ToArray();
                var m = new Memory&lt;byte&gt;(result);
                await cnt.Response.BodyWriter.WriteAsync(m);
            });
        });
    }

}

4. That is all


Posted

in

,

by

Tags:

Comments

2 responses to “Using files in a ASP.NET Core nuget package”

  1. Siderite Avatar

    Don’t you know the size of the file from the start? Why do you need buffering? Either way a buffer of 2000 bytes is very small and may be slow.

    1. Andrei Ignat Avatar
      Andrei Ignat

      right … IFileInfo has a length property … I will modify

Leave a Reply

Your email address will not be published. Required fields are marked *