2011-09-18 59 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要連接你的依賴注入框架。這樣,您的服務代碼不再依賴於託管服務的方式/位置。所有這個服務需要的是一個文件路徑=>注入它。