Accessing the complete server path for a file in a WCF web service
I have a web service with a svc file and a codebehind that defines a simple web service using WCF.
Obviously I am hosting the web service on a server using the svc file.
My service needs to access a file in the directory of the web application where the web service resides.
Consider that following structure:
Web application r开发者_如何学Gooot 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
Well. From the csharp file codebehind web service file I would like to access the xml file located in the appropriate folder for data.
How should I do this??? I cannot have access to a Server object of course...
Thankyou
If you are hosting in IIS:
var root = HostingEnvironment.ApplicationPhysicalPath;
var someFile = Path.Combine(root, "images", "test.png");
Now of course this being said you should absolutely never write such code in a WCF service operation. You should have this service take the path as constructor argument and then simply configure your dependency injection framework to pass the correct value:
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
}
}
Now all that's left is to write a custom IInstanceProvider to wire up your dependency injection framework. This way the code of your service is no longer dependent on how/where is the service hosted. All that this service needs is a file path => inject it into it.
精彩评论