asp.net-corerazorrazor-pagesrazor-class-library

Using reflection how do I list the contents of the wwwroot files in a Razor Class Library (RCL)


I have a Razor Class Library that I reference and I have the following structure.

wwwroot  
-- Css
--- styles.css  
-- Js
--- scripts.js

I can reference these files in the main project with the following URLs. If I browse to these URLs then I can see the file contents as expected.

./_content/Plugins/js/scripts.js  
./_content/Plugins/css/styles.css

Using reflection, I want to be able to look in the Assembly and get a list of all static assets. According to the documentation I have found online, I am supposed to be able to get a list of all the files using the following code

var assembly = Assembly.GetAssembly(typeof(MyClassInPlugins));
string[] names = assembly.GetManifestResourceNames();

However, this returns an empty array string[0], Which is unexpected as I know the assembly has static resources, as explained above.

So how do I get a list of all the static files/resources, in the wwwroot folder in a Razor Class Library? I'm using .Net 7 if that makes a difference.


Solution

  • Firstly, be sure all the static files in RCL/wwwroot has beed set Copy Always:

    enter image description here

    Then using the code to get the file relative path(e.g. /js/site.js):

    var assembly = Assembly.GetAssembly(typeof(YourClassInPlugins)).Location;
    string theDirectory = Path.GetDirectoryName(assembly);
    string folderPath = Path.Combine(theDirectory, "wwwroot");
    string[] allfiles = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories); //absolute path....
    var names = allfiles.Select(a => a.Split("wwwroot")[1]).ToList(); // relative path...