在我们部署的新ASP.NET核心世界中,我们有2个文件夹appRoot和wwwroot
我们通常只将文件放在我们打算直接用http请求服务的wwwroot文件夹下.因此,如果您的json文件是直接提供的,即客户端js使用,那么也许你会把它们放在那里,否则你会在appRoot下面使用不同的文件夹.
我将在下面展示如何解决这两种情况的路径,即示例代码如何将json字符串保存到appRoot或wwwroot下面的文件夹中.在这两种情况下都将您的位置视为相对于其中一个文件夹的虚拟路径,即/ some / folder / path其中第一个/表示appRoot或wwwroot
public class MyFileProcessor
{
public MyFileProcessor(IHostingEnvironment env,IApplicationEnvironment appEnv)
{
hostingEnvironment = env;
appEnvironment = appEnv;
appRootFolder = appEnv.ApplicationBasePath;
}
private IHostingEnvironment hostingEnvironment;
private IApplicationEnvironment appEnvironment;
private string appRootFolder;
public void SaveJsonToAppFolder(string appVirtualFolderPath,string fileName string jsonContent)
{
var pathToFile = appRootFolder + appVirtualFolderPath.Replace("/",Path.DirectorySeparatorChar.ToString())
+ fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
public void SaveJsonToWwwFolder(string virtualFolderPath,string fileName string jsonContent)
{
var pathToFile = hostingEnvironment.MapPath(virtualFolderPath) + fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
}