简体   繁体   English

ASP.NET MVC-尝试读写文本文件时出错

[英]ASP.NET MVC - error while trying to read and write to text file

currently I am trying to create two controller methods reading from file and writing to same file: 目前,我正在尝试创建两个从文件读取并写入同一文件的控制器方法:

public ActionResult UploadText(string name)
{
    var path = Path.Combine(Server.MapPath("~/text/"), name);

    var fileContents = System.IO.File.ReadAllText(path);
    ViewData["text"] = fileContents;
    ViewData["textName"] = name;

    return View();
}

[HttpPost]
public ActionResult TextPost(string textName)
{
    string text = Request["text-content"];
    var path = Path.Combine(Server.MapPath("~/text/"), textName);

    System.IO.File.WriteAllText(path, text);

    return RedirectToAction("Index");
}

Reading file content and writing to it works, but it cannot be read second time, File can't be accessed because it is being used by another process error appears. 可以读取文件内容并将其写入,但是无法第二次读取, File can't be accessed because it is being used by another process错误File can't be accessed because it is being used by another process

What am I doing wrong? 我究竟做错了什么?

System.IO.File.ReadAllText and System.IO.File.WriteAllText both close the file after they and finished with the file per the documentation . System.IO.File.ReadAllText和System.IO.File.WriteAllText都在它们关闭后关闭文件,并根据文档完成该文件 The issue stems from the async nature of the web and well if you have more than one request while the file is open you will get the error you are seeing. 该问题源于Web的异步特性,如果文件打开时有多个请求,您将收到所看到的错误。 Here are some MSDN examples to get you started. 这是一些MSDN示例 ,可以帮助您入门。

Here are a couple more links for your pleasure 这里有几个链接供您欣赏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM