【问题标题】:Could not find path in the web application在 Web 应用程序中找不到路径
【发布时间】:2013-11-27 11:22:16
【问题描述】:

我正在尝试使用以下代码使用ASP.NET 4.5 with c# 写入文本文件:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"./Experiment/main.txt", true))
{
file.WriteLine(DateTime.UtcNow.ToString() + " test");
}

我得到了这个例外:

"Could not find a part of the path 'C:\Windows\SysWOW64\inetsrv\Experiment\main.txt'."

文件夹Experiment 是我的网络应用程序的文件夹。

【问题讨论】:

  • 当您在 ASP.NET 中使用相对路径时,它使用的工作目录不是您的 Web 根目录,而是运行 IIS 的位置。

标签: c# asp.net streamwriter


【解决方案1】:

您需要提供物理路径而不是相对路径,使用Server.MapPath("~") 获取站点的根路径,然后将文件路径附加到它。您可以在此post 中了解有关 Server.MapPath 的更多信息。

using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath(@"~/Experiment/main.txt"), true))
{
     file.WriteLine(DateTime.UtcNow.ToString() + " test");
}

【讨论】:

    【解决方案2】:

    试试这个代码

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory+"Experiment/main.txt", true))
    {
             DirectoryInfo dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+"Experiment/main.txt");
                if (!dirInfo.Exists)
                {
                    dirInfo.Create();
                }
         file.WriteLine(DateTime.UtcNow.ToString() + " test");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      相关资源
      最近更新 更多