asp.net中獲取網站根目錄和物理路徑的方法


 1         /// <summary>
 2         /// 取得網站的根目錄的URL
 3         /// </summary>
 4         /// <returns></returns>
 5         public static string GetRootURI()
 6         {
 7             string AppPath = "";
 8             HttpContext HttpCurrent = HttpContext.Current;
 9             HttpRequest Req;
10             if (HttpCurrent != null)
11             {
12                 Req = HttpCurrent.Request;
13 
14                 string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
15                 if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
16                     //直接安裝在   Web   站點   
17                     AppPath = UrlAuthority;
18                 else
19                     //安裝在虛擬子目錄下   
20                     AppPath = UrlAuthority + Req.ApplicationPath;
21             }
22             return AppPath;
23         }
24         /// <summary>
25         /// 取得網站的根目錄的URL
26         /// </summary>
27         /// <param name="Req"></param>
28         /// <returns></returns>
29         public static string GetRootURI(HttpRequest Req)
30         {
31             string AppPath = "";
32             if (Req != null)
33             {
34                 string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
35                 if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
36                     //直接安裝在   Web   站點   
37                     AppPath = UrlAuthority;
38                 else
39                     //安裝在虛擬子目錄下   
40                     AppPath = UrlAuthority + Req.ApplicationPath;
41             }
42             return AppPath;
43         }
44         /// <summary>
45         /// 取得網站根目錄的物理路徑
46         /// </summary>
47         /// <returns></returns>
48         public static string GetRootPath()
49         {
50             string AppPath = "";
51             HttpContext HttpCurrent = HttpContext.Current;
52             if (HttpCurrent != null)
53             {
54                 AppPath = HttpCurrent.Server.MapPath("~");
55             }
56             else
57             {
58                 AppPath = AppDomain.CurrentDomain.BaseDirectory;
59                 if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
60                     AppPath = AppPath.Substring(0, AppPath.Length - 1);
61             }
62             return AppPath;
63         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM