[英]Get Physical path of Virtual Directory in Window Service
In my IIS server I have a Virtual Directory ("docPath") which is mapped with a physical folder of my machine. 在我的IIS服务器中,我有一个虚拟目录 (“docPath”) ,它与我的机器的物理文件夹映射。
I have a Window Service and from this service I need to get the Physical path of Virtual directory (created on IIS) ie "docPath" . 我有一个Window服务 ,从这个服务我需要获取虚拟目录的物理路径(在IIS上创建),即“docPath” 。
Since this is Windows service so I do not have HTTPContext object and I cannot use the HttpContext.Current.Server.MapPath("/docPath");
由于这是Windows服务,所以我没有HTTPContext对象,我不能使用HttpContext.Current.Server.MapPath("/docPath");
This is what I've tried so far: 这是我到目前为止所尝试的:
I have tried to use the ServerManager from Microsoft.Web.Administration . 我曾尝试使用Microsoft.Web.Administration中的ServerManager 。
ServerManager serverManager = new ServerManager();
Site site = serverManager.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
Application myApp = site.Applications["/docPath"];
But in Sites only web application created on IIS server are coming and not Virtual directories. 但在站点中,只有在IIS服务器上创建的Web应用程序才会出现而不是虚拟目录。
Also, System.Web.Hosting.HostingEnvironment.MapPath
is also not working. 此外, System.Web.Hosting.HostingEnvironment.MapPath
也无法正常工作。
Could anybody let me know how can I get physical path of a Virtual Directory in Windows Service? 有谁能让我知道如何在Windows服务中获取虚拟目录的物理路径?
Add a generic handler to your web app, then have it return to you the physical path. 向您的Web应用程序添加通用处理程序,然后让它返回物理路径。 In the generic handler you can have this code. 在通用处理程序中,您可以拥有此代码。
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;
}
}
}
}
Then you can use it like this in the windows service. 然后你可以在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();
}
Remember to include the following namespaces into the windows service 请记住将以下命名空间包含在Windows服务中
using System.IO;
using System.Net;
using System.Text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.