以下方法通常有效,但有时会抛出异常。我不知道为什么,因为它大部分时间都是有效的。也许是因为我使用美元符号将变量插入到字符串中。有没有人能告诉我怎样才能以不同的方式来避免这个错误?
我得到的异常:
Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Path '', line 0, position 0.'
方法:
public RetrieveModels(string path)
{
JArray json = JArray.Parse(File.ReadAllText($@"{path}"));
[...]
}路径类似于:"C:\\Users\\ZAT\\source\\repos\\tool\\tool\\wwwroot\\processes.json"
我在控制器中的以下Action方法中创建了路径:
public IActionResult UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
else
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"processes.json");
using (var stream = new FileStream(path, FileMode.Create))
{
file.CopyToAsync(stream);
}
RetrieveModels rm = new RetrieveModels(path);
[...]
}
}它也可能在文件尚未创建或正在创建时尝试解析该文件。因此,我尝试将rm = new RetrieveModels(path);放在file.CopyToAsync(stream);之下,但这导致了另一个异常,说明我无法访问该文件,因为它正被另一个进程使用。
发布于 2018-02-02 16:33:47
我想我通过使用async和await解决了这个问题
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
else
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"processes.json");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
RetrieveModels rm = rm = new RetrieveModels(path);
[...]
}
}https://stackoverflow.com/questions/48544542
复制相似问题