【问题标题】:File.Exists using the wrong root path?File.Exists 使用错误的根路径?
【发布时间】:2011-03-17 19:55:53
【问题描述】:

在我编写的 c# 类中,我有一个 photo 属性,如果图像存在则返回照片源(否则不存在或默认图像)。在我的代码中我使用:

    public string Photo
    {
        get
        {
            string source = "~/images/recipes/" + id + ".jpg";

            if (File.Exists(source))
                return "~/images/recipes/" + id + ".jpg";
            else
                return "";
        }
    }

如果我获得此图像的 FileInfo() 信息,我发现我尝试在以下目录中找到此图像:C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\ ~\images\recipes

当然,图像不在该目录中,并且 File.Exists 返回了错误的值。但是我该如何解决这个问题?

【问题讨论】:

  • 这个问题被重新标记(我猜?)到 ASP.NET 但您需要指定这是否确实是 ASP 或者您正在尝试让 Unix '~/' 约定在 Windows 上工作。
  • 最初的问题标题引用了 ASP.NET,上下文使问题看起来像是关于使用 '~/' 作为应用程序根,而不是 Unix 约定。

标签: c# asp.net


【解决方案1】:

试试这个:

if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))

【讨论】:

  • 我无法访问此类中的 Server 对象。
  • System.Web.HttpContext.Current.Server.MapPath 的工作方式与Server.MapPath 相同。
【解决方案2】:

您需要将相对路径映射回物理路径:

string source = HttpContext.Current.Server.MapPath("~/images/recipes/" + id + ".jpg");

【讨论】:

    【解决方案3】:

    你必须使用:

    Server.MapPath(source)
    

    因为您无法 100% 确定代码将从何处运行,即。它在开发和生产服务器上会有所不同。你也确定 ~/ 在 Windows 中工作吗?这不会被解释为一个名为 ~ 的目录吗?除非那是你想要的。

    【讨论】:

    • Server.MapPath 应该将 '~' 解释为 'ApplicationRoot'。否则,是的,它被视为目录名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多