首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从JsonReader读取JArray时出错

从JsonReader读取JArray时出错
EN

Stack Overflow用户
提问于 2018-01-31 22:27:56
回答 1查看 1.2K关注 0票数 1

以下方法通常有效,但有时会抛出异常。我不知道为什么,因为它大部分时间都是有效的。也许是因为我使用美元符号将变量插入到字符串中。有没有人能告诉我怎样才能以不同的方式来避免这个错误?

我得到的异常:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Path '', line 0, position 0.'

方法:

代码语言:javascript
复制
public RetrieveModels(string path)
{
    JArray json = JArray.Parse(File.ReadAllText($@"{path}"));
    [...]
}

路径类似于:"C:\\Users\\ZAT\\source\\repos\\tool\\tool\\wwwroot\\processes.json"

我在控制器中的以下Action方法中创建了路径:

代码语言:javascript
复制
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);之下,但这导致了另一个异常,说明我无法访问该文件,因为它正被另一个进程使用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-02 16:33:47

我想我通过使用asyncawait解决了这个问题

代码语言:javascript
复制
[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);
        [...]
    }           
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48544542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档