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
Please try with below code sample :
var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\UploadFile");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
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);
}
}
-
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.– AliRamCommented 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 BCommented 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"); }
Thepath
will be your path variable that you created from the code before– Ivan BCommented Aug 22, 2019 at 13:30