0

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.

What am I doing wrong?

Marcin Zdunek
  • 1,001
  • 1
  • 10
  • 25

1 Answers1

0

System.IO.File.ReadAllText and System.IO.File.WriteAllText both close the file after they and finished with the file per the documentation. 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. Here are some MSDN examples to get you started.

Here are a couple more links for your pleasure

Community
  • 1
  • 1
Craig Selbert
  • 737
  • 1
  • 8
  • 17