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
;
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public static void UseBlocklyUI( this IApplicationBuilder appBuilder) { var manifestEmbeddedProvider = new ManifestEmbeddedFileProvider(Assembly.GetExecutingAssembly()); var service = appBuilder.ApplicationServices; mapFile( "blocklyAutomation" , 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 + "/" + item.Name, provider, appBuilder); continue ; } string map = (dirName + "/" + item.Name).Substring(dirName.Length); appBuilder.Map(map, app => { var f = item; app.Run( async cnt => { //TODO: find from extension //cnt.Response.ContentType = "text/html"; 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)) > 0) { stream.Write(buffer, 0, bytesRead); } byte [] result = stream.ToArray(); var m = new Memory< byte >(result); await cnt.Response.BodyWriter.WriteAsync(m); }); }); } } |
4. That is all
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.
right … IFileInfo has a length property … I will modify