2013-02-18 79 views
1

当我尝试运行此给我类字段例外如下所示:为MapPath的字段对象参考

一个对象引用是所必需的非静态字段,方法或 属性“的System.Web .UI.Page.MapPath(string)

为什么?

后面的代码:

public partial class Profile : System.Web.UI.Page 
{ 
    DirectoryInfo dir = new DirectoryInfo(MapPath("~/pic")); 

回答

1
DirectoryInfo dir = new DirectoryInfo(
HttpContext.Current.Request.PhysicalApplicationPath + "\\pic")); 
+0

现在工作。你能解释一下为什么,问题的原因是什么? – TheChampp 2013-02-18 18:49:52

+2

@Win或'@“\ pic”' – DiskJunky 2013-02-18 18:50:12

+0

正如DiskJunky所说,您也可以使用'at'符号。 TheCampp - 它基本上返回您的网站的实际文件夹内的图片文件夹。例如,c:\ wwwroot \ yoursite \ pic – Win 2013-02-18 18:52:23

0

MSDN文档:

...在路径开头的斜线(/)指示到现场的绝对虚拟路径。

所以你的“〜”是错误的和不必要的。

+0

我删除,并再次同样的问题。 – TheChampp 2013-02-18 18:43:31

+0

@ TheChampp是MapPath(“/ pic”)返回一个有效的结果吗? – 2013-02-18 18:46:14

1

尝试Server.MapPath()HttpContext.Current.Server.MapPath()