当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET编程获取网站根目录方法小结

ASP.NET编程获取网站根目录方法小结

2017年12月12日  | 移动技术网IT编程  | 我要评论

广西师范大学漓江学院,固相萃取仪,3499单人小游戏

本文实例讲述了asp.net编程获取网站根目录方法。分享给大家供大家参考,具体如下:

获取网站根目录的方法有几种如:

server.mappath(request.servervariables["path_info"])
server.mappath("/")
server.mappath("")//当前代码文件所在的目录路劲
server.mappath(".")
server.mappath("../")
server.mappath("..") 
page.request.applicationpath

以上的代码在http://localhost/englishclub/manage/webform1.aspx页面

运行结果:

c:\inetpub\wwwroot\englishclub\manage\webform1.aspx
c:\inetpub\wwwroot\
c:\inetpub\wwwroot\englishclub\manage
c:\inetpub\wwwroot\englishclub\manage
c:\inetpub\wwwroot\englishclub\
c:\inetpub\wwwroot\englishclub

以上的方法可以在.aspx中访问,但是如果你在。cs文件就不能用。

httpcontext.current.server.mappath();
system.web.httpcontext.current.request.physicalapplicationpath

在.cs文件中可以用。但是httpcontext.current.server.mappath();这个获取的是文件的路径而不是根目录。

只有system.web.httpcontext.current.request.physicalapplicationpath 这个才是获取的根目录,在写获取数据库路径是应该用这个,其他的都有问题。

system.web.httpcontext.current.request.physicalapplicationpath
和server.mappath("~/")效果是一样的。

server.mappath("~/");//无论代码所在的文件的、页面路劲是什么,永远返回 c:\inetpub\wwwroot\englishclub\(就是当前程序运行的所在根目录)

如果存储 附件的路劲 进数据库的话,不应该把绝对路劲存进去。应该只存储 文件名部分。例如:

/uploads/abc.txt
当需要浏览文件的时候,在在读取出来的路径:(即/uploads/abc.txt),前面+网站的路劲:例如:

http://abc.com+"/uploads/abc.txt"

补充:

asp.net中获取网站根目录和物理路径完整实例:

/// <summary>
/// 取得网站的根目录的url
/// </summary>
/// <returns></returns>
public static string getrooturi()
{
  string apppath = "";
  httpcontext httpcurrent = httpcontext.current;
  httprequest req;
  if (httpcurrent != null)
  {
    req = httpcurrent.request;
    string urlauthority = req.url.getleftpart(uripartial.authority);
    if (req.applicationpath == null || req.applicationpath == "/")
      //直接安装在  web  站点  
      apppath = urlauthority;
    else
      //安装在虚拟子目录下  
      apppath = urlauthority + req.applicationpath;
  }
  return apppath;
}
/// <summary>
/// 取得网站的根目录的url
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public static string getrooturi(httprequest req)
{
  string apppath = "";
  if(req != null)
  {
    string urlauthority = req.url.getleftpart(uripartial.authority);
    if (req.applicationpath == null || req.applicationpath == "/")
      //直接安装在  web  站点  
      apppath = urlauthority;
    else
      //安装在虚拟子目录下  
      apppath = urlauthority + req.applicationpath;
  }
  return apppath;
}
/// <summary>
/// 取得网站根目录的物理路径
/// </summary>
/// <returns></returns>
public static string getrootpath()
{
  string apppath = "";
  httpcontext httpcurrent = httpcontext.current;
  if (httpcurrent != null)
  {
    apppath = httpcurrent.server.mappath("~");
  }
  else
  {
    apppath = appdomain.currentdomain.basedirectory;
    if (regex.match(apppath, @"\\$", regexoptions.compiled).success)
      apppath = apppath.substring(0, apppath.length - 1);
  }
  return apppath;
}

希望本文所述对大家asp.net程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网