我正在尝试实现一个服务器控件,该控件可以访问ASP.NET站点的Web目录中的几个文件。我使用VS Web Dev Express 2008作为我的IDE。当我调用HttpContext.Current.Request.ApplicationPath
获取Web根路径以便我可以找到这些文件时,它返回C:。到底是什么?
绝对路径工作正常,但我希望能够为服务器控件提供一个相对目录,让它做到这一点。我做错了什么?
public String Target
{
get { return _target; }
set
{
if (value.StartsWith("~"))
{
// WTF? Gives me C:\? Why?
_target = HttpContext.Current.Request.ApplicationPath +
value.Substring(1);
}
else
{
_target = value;
}
}
}
private String _target;
protected override void Render(HtmlTextWriter writer)
{
HtmlControl wrapper = new HtmlGenericControl("div");
int fileCount = 0;
try
{
DirectoryInfo dir = new DirectoryInfo(_target);
foreach (FileInfo f in dir.GetFiles())
{
fileCount++;
a = new HtmlAnchor();
a.Attributes.Add("href", f.FullName);
a.InnerHtml = f.Name;
wrapper.Controls.Add(a);
}
}
catch (IOException e)
{
throw e;
}
Controls.Add(wrapper);
base.Render(writer);
}
答案 0 :(得分:3)
这可能是因为它正在使用开发Web服务器,它只能从硬盘驱动器上的任何目录提供文件。它没有任何特定的根。你可以在IIS下运行你的项目(假设你的Windows版本支持它),看看你是否得到相同的结果?
要完全摆脱这个问题,您可以在web.config中对要查看的路径进行硬编码,并解决Request.ApplicationPath返回的任何问题。
[编辑]
刚刚发现你可以使用
HTTPContext.Current.Request.ServerVariables("APPL_PHYSICAL_PATH")
在硬盘上返回应用程序的路径。我很确定这就是你要找的东西。如果那不对,请查看所有其他ServerVariables,看看您是否能得到您想要的内容。
答案 1 :(得分:2)
这个怎么样:
Server.MapPath(ResolveUrl("~/filename"))
还有TLAnews.com页面上标题为Understanding Paths in ASP.NET的信息。
答案 2 :(得分:-1)
如果您在设计时尝试获取目录,ADME Developer's Kit可能就是您所需要的。