[英]Get Physical path of Virtual Directory in Window Service
在我的IIS服務器中,我有一個虛擬目錄 (“docPath”) ,它與我的機器的物理文件夾映射。
我有一個Window服務 ,從這個服務我需要獲取虛擬目錄的物理路徑(在IIS上創建),即“docPath” 。
由於這是Windows服務,所以我沒有HTTPContext對象,我不能使用HttpContext.Current.Server.MapPath("/docPath");
這是我到目前為止所嘗試的:
我曾嘗試使用Microsoft.Web.Administration中的ServerManager 。
ServerManager serverManager = new ServerManager();
Site site = serverManager.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
Application myApp = site.Applications["/docPath"];
但在站點中,只有在IIS服務器上創建的Web應用程序才會出現而不是虛擬目錄。
此外, System.Web.Hosting.HostingEnvironment.MapPath
也無法正常工作。
有誰能讓我知道如何在Windows服務中獲取虛擬目錄的物理路徑?
向您的Web應用程序添加通用處理程序,然后讓它返回物理路徑。 在通用處理程序中,您可以擁有此代碼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2
{
/// <summary>
/// Summary description for PhysicalPathHandler
/// </summary>
public class PhysicalPathHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(HttpContext.Current.Server.MapPath("docPath"));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
然后你可以在Windows服務中使用它。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("your-web-app-web-address-to-the-generic-handler"); //e.g. http://localhost:2950/PhysicalPathHandler.ashx
string physicalPath = string.Empty; //this will store the physical path
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream, encoding))
physicalPath= reader.ReadToEnd();
}
請記住將以下命名空間包含在Windows服務中
using System.IO;
using System.Net;
using System.Text;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.