繁体   English   中英

获取Window Service中虚拟目录的物理路径

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM