[英]System.IO.FileNotFoundException: 'Could not find file (but file exists in the project)
I have taken a static list and added product data into a data.json inside wwwroot and data is being saved but while I'm trying to read data from the file, getting above exception.我已经获取了 static 列表并将产品数据添加到 wwwroot 内的 data.json 中,并且正在保存数据,但是当我尝试从文件中读取数据时,出现了上述异常。 This is my controller code
这是我的 controller 代码
public class ProductController: Controller {公共 class 产品控制器:Controller {
static List<ProductGeneral> productDetails = new List<ProductGeneral>();
private IWebHostEnvironment WebHostEnvironment;
public ProductController(IWebHostEnvironment webHostEnvironment)
{
WebHostEnvironment = webHostEnvironment;
}
public ActionResult CreateData(ProductGeneral model)
{
if (model != null && ModelState.IsValid )
{
productDetails.Add(model);
string data = JsonConvert.SerializeObject(productDetails, Formatting.Indented);
CreateFile(data);
return View("ShowData", productDetails);
}
else
{
return View();
}
}
public void CreateFile(string data)
{
string uploadDir = Path.Combine(WebHostEnvironment.WebRootPath);
var fileName = "data.json";
string filePath = Path.Combine(uploadDir, fileName);
System.IO.File.WriteAllText(filePath, data);
}
public ActionResult ShowData()
{
//string RootPath = WebHostEnvironment.WebRootPath;
//var JSON = System.IO.File.ReadAllText(RootPath + @"\Json\c356896b-5025-47b3-a049-662f2098be52");
//return View(JSON);
string RootPath = WebHostEnvironment.WebRootPath;
var data = System.IO.File.ReadAllText(RootPath + @"data.json");
if (!string.IsNullOrEmpty(data))
{
productDetails = JsonConvert.DeserializeObject<List<ProductGeneral>>(data);
}
return View(productDetails);
}
}
In the ShowData()
method it is necessary to use Path.Combine()
to generate correct path_filename
as you did in the CreateFile()
:在
ShowData()
方法中,有必要像在CreateFile()
中那样使用Path.Combine()
生成正确的path_filename
:
var path = Path.Combine(WebHostEnvironment.WebRootPath, "data.json");
var data = System.IO.File.ReadAllText(path);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.