一、獲取網站根目錄的方法有幾種如:
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文件就不能用。
下面兩個都可以在.cs文件中用:
HttpContext.Current.Server.MapPath();//所在文件夾路徑 System.Web.HttpContext.Current.Request.PhysicalApplicationPat;//根路徑
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"
二.線程中獲取系統路徑
以上都是在web程序引用下獲取路徑,
在多線程里面使用HttpContext.Current,HttpContext.Current是得到null的.
所以以上方法在線程中直接使用是不行的。
在線程中得到系統根路徑可以用此方法:
public static string MapPath(string strPath) { if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\")) { //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\'); strPath = strPath.TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } }