ReadAllLines找不到我的文本文件路径? (ASP.NET MVC)

每当执行使用相应ActionResult的代码时,我的程序都会引发以下异常错误,如下所示:

“ System.IO.DirectoryNotFoundException:'找不到路径'...'的一部分

enter image description here

我非常有信心我使用了正确的路径,因为我已经使用完全相同的路径直接从另一个控制器复制了它。

以下是在执行过程中调用此特定路径所使用的操作结果:

public ActionResult DeleteItemLine(string ReferenceDelete)
        {
            // 1. Read the content of the file
            string[] readLineItems = System.IO.File.ReadAllLines("~/App_Data/Item.txt");

            // 2. Empty the file
            System.IO.File.WriteAllText("~/App_Data/Item.txt", string.Empty);

            // 3. Fill up again, but without the deleted line
            using (StreamWriter writeItems = new StreamWriter("~/App_Data/Item.txt"))
            {
                foreach (string line in readLineItems)
                {
                    if(!line.Equals(ReferenceDelete))
                    {
                        writeItems.WriteLine(line);
                    }
                }
            }

            return View();
        }

我在这里很想念任何明显的东西吗?任何指导将不胜感激。非常感谢!

评论
  • eut
    eut 回复

    Looks like System.IO.File.ReadAllLines("~/App_Data/Item.txt") doesn't understand what ~ means and is based on the root of the server, not the project.

    You need to use Server.MapPath(), this will accept paths relative to the project.

    用这个;

    string[] readLineItems = System.IO.File.ReadAllLines(Server.MapPath("~/App_Data/Item.txt"));