从JsonReader

时间:2018-01-31 14:27:56

标签: c# asp.net .net asp.net-mvc json.net

以下方法通常有效,但有时它会引发异常。我不确定为什么,因为它大部分时间都有效。也许是因为我使用美元符号将变量插入字符串中。有人可以告诉我如何以不同的方式做到这一点以避免错误吗?

我得到例外:

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);之下,但这导致另一个例外,即我无法访问该文件,因为它正由另一个进程使用。

1 个答案:

答案 0 :(得分:2)

我认为我使用asyncawait来解决了这个问题:

[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);
        [...]
    }           
}