2011-09-18 50 views
1

我有一个带有svc文件和代码隐藏的Web服务,它定义了一个使用WCF的简单Web服务。在WCF Web服务中访问文件的完整服务器路径

很明显,我在使用svc文件的服务器上托管Web服务。

我的服务需要访问Web服务所在Web应用程序的目录中的文件。

请考虑以下结构:

Web application root folder: MyWebApp 

MyWebApp (folder) -> Images (folder) 

MyWebApp (folder) -> App_Code (folder) 

MyWebApp (folder) -> WebServices (folder) 

MyWebApp (folder) -> Data (folder) 

MyWebApp (folder) -> Web.config (file) 

MyWebApp (folder) -> WebServices (folder) -> MyWebService.svc (file) 

MyWebApp (folder) -> App_Code (folder) -> MyWebService.cs (file) 

MyWebApp (folder) -> Data (folder) -> myfile.txt 

嘛。从csharp文件代码隐藏的web服务文件中,我想访问位于适当数据文件夹中的xml文件。

我应该怎么做?我不能访问过程中的Server对象...

三江源

回答

4

如果你正在主持在IIS:

var root = HostingEnvironment.ApplicationPhysicalPath; 
var someFile = Path.Combine(root, "images", "test.png"); 

现在当然这是说,你应该绝对不会写这样的代码一个WCF服务操作。你应该有这项服务采取的路径作为构造函数的参数,然后简单地配置您的依赖注入框架来传递正确的值:

public class MyService1: IMyService 
{ 
    private readonly string _path; 
    public MyService1(string path) 
    { 
     _path = path; 
    } 

    public void SomeServiceOperation() 
    { 
     var someFile = Path.Combine(_path, "images", "test.png"); 
     // TODO: do something with the file 
    } 
} 

现在,所有剩下的就是写一个custom IInstanceProvider要连接你的依赖注入框架。这样,您的服务代码不再依赖于托管服务的方式/位置。所有这个服务需要的是一个文件路径=>注入它。