2

How to create a folder in wwwroot by coding? im use asp core 2.2 this code not working: Path.Combine(_hostingEnvironment.WebRootPath, "wwwroot\UploadFile");a

2 Answers 2

5

Please try with below code sample :

var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\UploadFile");
if (!Directory.Exists(filePath))
{
    Directory.CreateDirectory(filePath);
}
1

Path.Combine will only give you the path string. It won't create a directory by itself.

I suggest passing IHostingEnvironment to your class through dependency injection and then using WebRootPath to get the path for wwwroot folder (i.e. not hardcoding it).

public class YourClass
{
   private readonly IHostingEnvironment _env;

   public YourClass(IHostingEnvironment env)
   {
       _env = env;
   }

   public YourMethod()
   {
       string path = Path.Combine(_env.WebRootPath, "UploadFile").ToLower();

       //if path does not exist -> create it
       if (!Directory.Exists(path)) Directory.CreateDirectory(path);
   }
}
3
  • i use this code @ivan B and directory is created in phisycal root but not maped in visual sdudio and not show to wwwroot folder on the visual studio.
    – AliRam
    Commented Aug 22, 2019 at 13:20
  • @AliRamezani Are you creating this folder so that to write files into it? Try creating file in that folder. In my project I create folder and then create new file in it. Then Visual Studio shows that new folder and file in Solution Explorer.
    – Ivan B
    Commented Aug 22, 2019 at 13:26
  • Try doing this: string fullPath = Path.Combine(path, "myFile.txt"); using (StreamWriter fileStream = new StreamWriter(fullPath)) { fileStream.Write("Some text here"); } The path will be your path variable that you created from the code before
    – Ivan B
    Commented Aug 22, 2019 at 13:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.