Most of programmers who are dealing with ASP.NET know how to access files on the server. The common way how to do this is to use HttpContext.Current.Server.MapPath static method and get physical path of the file by passing virtual. But what if we need for instance to read some data from text file which located in our project in Design Time mode. Server.MapPath won't help us so much as our application is not hosted by IIS or Cassini and HttpContext didn't fill yet. How to get physical path of the file then? Thanks to .Net 2.0 it is simple.
For instance let's try to get physical path of the file (sample.txt) stored in the root directory of project thru server control .
To achieve our goal we need three players ISite, IWebApplication and IProjectItem.
ISite - Gets information about the container that hosts the current control when rendered on a design surface.
We have this property available in control level (Control.Site). Be aware Site property is filled only in design time mode and not available when application hosted under the IIS or Cassini.
IWebApplication - IServiceProvider based interface which provides access to Web application in Design Mode.
By using this service we have ability to access items in our projects and reading web.config file in Design Mode.
IProjectItem - Provides an interface for an item that is retrieved at design time.
Contains such information as physical path, virtual path, name etc
Step 1.
First we have to get IWebApplication service from the list of running services.
IWebApplication webApp = (IWebApplication)Site.GetService(typeof(IWebApplication));
Step 2.
Get project item by calling appropriate method.
IProjectItem item = webApp.GetProjectItemFromUrl("~/sample.txt");
Step 3.
Then just get information about physical path from property of IProjectItem interface.
string filePhysicalPath = item.PhysicalPath;
That is it. Easy isn't it, but big headache for the programmers who need that and doesn't know about it. :)
1 comment:
You rock! I was beating my head against the wall about this one.
Post a Comment