Create folders in wwwroot on startup in NetCore

1.1k Views Asked by At

Is there a way to create folders in wwwroot when the application startup? Perhaps in the startup.cs class?

I know how to create folders in wwwroot in controller action methods. I do not want this.

This is what I would like:

  • I have a List of Objects: List<Organization> Organizations
  • foreach (Organization in Organization) I want a folder with the Organization.Name created in the wwwroot folder
  • I would like it to be created at the moment the application is launched

Thanks in advance you for any help

2

There are 2 best solutions below

0
On

Is there a way to create folders in wwwroot when the application startup? Perhaps in the startup.cs class?

To achieve the requirement, you can try to inject IHostApplicationLifetime into Configure() method and write the callback for ApplicationStarted, then you can create folder(s) based on List<Organization> Organizations.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{
    //...
    //your code here

    lifetime.ApplicationStarted.Register(OnApplicationStartedAsync(env).Wait);

    //...
}

private async Task<Action> OnApplicationStartedAsync(IWebHostEnvironment env)
{
    foreach (var org in Organizations)
    {
        var path = Path.Combine(env.WebRootPath, $"{org.Name}");

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    }
           

    return null;
}
0
On

you can use the following

but please note that you have duplicate variable names in your foreach

var rootFolder=Path.Combine(Directory.GetCurrentDirectory(),"wwwroot");
foreach (org in Organizations){
    var orgFolderPath=Path.Combine(rootfolder,org.Name);
    if(!Directory.Exists(orgFolderPath){
        Directory.CreateDirectory(orgFolderPath);
    }
}