0

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

4

2 回答 2

0

有没有办法在应用程序启动时在 wwwroot 中创建文件夹?也许在 startup.cs 类中?

为了达到要求,您可以尝试注入IHostApplicationLifetime方法Configure()并为 编写回调ApplicationStarted,然后您可以基于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;
}
于 2021-01-27T06:03:12.440 回答
0

你可以使用以下

但请注意,您的 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);
    }
}
于 2021-01-26T10:25:53.060 回答