Export (0) Print
Expand All
9 out of 12 rated this helpful - Rate this topic

VirtualPathProvider Class

Provides a set of methods that enable a Web application to retrieve resources from a virtual file system.

Namespace:  System.Web.Hosting
Assembly:  System.Web (in System.Web.dll)
'Declaration
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Medium)> _
<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.High)> _
Public MustInherit Class VirtualPathProvider _
	Inherits MarshalByRefObject
'Usage
Dim instance As VirtualPathProvider

The VirtualPathProvider class provides a set of methods for implementing a virtual file system for a Web application. In a virtual file system, the files and directories are managed by a data store other than the file system provided by the server's operating system. For example, you can use a virtual file system to store content in a SQL Server database.

You can store any file that is processed on request in a virtual file system. This includes:

  • ASP.NET pages, master pages, user controls, and other objects.

  • Standard Web pages with extensions such as .htm and .jpg.

  • Any custom extension mapped to a BuildProvider instance.

  • Any named theme in the App_Theme folder.

You cannot store ASP.NET application folders or files that generate application-level assemblies in a virtual file system. This includes:

  • The Global.asax file.

  • Web.config files.

  • Site map data files used by the XmlSiteMapProvider.

  • Directories that contain application assemblies or that generate application assemblies: Bin, App_Code, App_GlobalResources, any App_LocalResources.

  • The application data folder, App_Data.

NoteNote:

If a Web site is precompiled for deployment, content provided by a VirtualPathProvider instance is not compiled, and no VirtualPathProvider instances are used by the precompiled site.

Registering a VirtualPathProvider

A custom VirtualPathProvider instance should be registered with the ASP.NET compilation system by using the HostingEnvironment.RegisterVirtualPathProvider method before any page parsing or compilation is performed by the Web application.

Typically, a VirtualPathProvider instance is registered in an AppInitialize method defined in the App_Code directory, or during the Application_Start event in the Global.asax file. For an example of registering a VirtualPathProvider instance in an AppInitialize method, see the Example section.

You can register a VirtualPathProvider instance during other events, but pages compiled and cached before the VirtualPathProvider instance is registered will not be invalidated, even if the new VirtualPathProvider instance would now provide the source for the previously compiled page.

Notes to Inheritors:

When you inherit from VirtualPathProvider, you must override the following members:

If your custom VirtualPathProvider class supports directories in the virtual file system, you must override the following members.

NoteNote:

If your virtual file system will contain themes for the Web site (by creating a virtual App_Themes directory), your custom VirtualPathProvider class must support directories.

A custom VirtualPathProvider class works with classes derived from the VirtualFile and VirtualDirectory classes. You should implement derived classes from these types to provide file and directory information from your virtual file system. For an example of a custom VirtualFile implementation, see the Example section of the VirtualFile class overview topic. For an example of a custom VirtualDirectory implementation, see the Example section of the VirtualDirectory class overview topic.

The following code example is a VirtualPathProvider class implementation that creates a virtual file system using information stored in a DataSet object. The code example works with the code examples for the VirtualFile and VirtualDirectory classes to provide virtual resources from a data store that is loaded into a DataSet object.

This example has four parts: the VirtualPathProvider class implementation, an XML data file used to populate the DataSet object, an AppStart object that contains an AppInitialize method used to register the VirtualPathProvider class with the compilation system, and an ASP.NET page that provides links to the virtual files.

To use this sample code in an application, follow these steps.

  1. Create a sample application on your Web server.

  2. Copy the source code for the custom VirtualPathProvider object (see below) into a file in the application's App_Code directory.

  3. Copy the source code for the custom VirtualDirectory object (see the Example section in the VirtualDirectory class overview topic) into a file in the application's App_Code directory.

  4. Copy the source code for the custom VirtualFile object (see the Example section in the VirtualFile class overview topic) into a file in the application's App_Code directory.

  5. Copy the source code for the AppStart object (see below) into a file in the application's App_Code directory.

  6. Copy the XML data (see below) into a file named XMLData.xml into a file in the application's App_Data directory.

  7. Copy the default.aspx file (see below) into the root directory of the sample application. Use a Web browser to open the default.aspx file, and then click the links on the page to see the contents of the virtual files.

The first example is a custom VirtualPathProvider class. The DirectoryExists and FileExists methods are overridden to indicate whether a requested directory is present in the virtual file system. The GetDirectory and GetFile methods are overridden to return custom VirtualDirectory and VirtualFile instances containing information from the virtual file system.

The class also provides a GetVirtualData method used by the VirtualDirectory and VirtualFile classes to access the DataSet object containing the virtual file system data. In a production implementation, this method would typically be implemented in a business object responsible for interacting with the data store.

Imports Microsoft.VisualBasic

Imports System
Imports System.Data
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.Caching
Imports System.Web.Hosting


Namespace Samples.AspNet.VB
  <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Medium), _
   AspNetHostingPermission(SecurityAction.InheritanceDemand, level:=AspNetHostingPermissionLevel.High)> _
  Public Class SamplePathProvider
    Inherits VirtualPathProvider

    Private dataFile As String 

    Public Sub New()
      MyBase.New()
    End Sub 

    Protected Overrides Sub Initialize()
      ' Set the datafile path relative to the application's path.
      dataFile = HostingEnvironment.ApplicationPhysicalPath & _
        "App_Data\XMLData.xml" 
    End Sub 

    ' <summary> 
    '   Data set provider for the SampleVirtualFile and 
    '   SampleVirtualDirectory classes. In a production application 
    '   this method would be on a provider class that accesses 
    '   the virtual resource data source. 
    ' </summary> 
    ' <returns> 
    '   The System.Data.DataSet containing the virtual resources 
    '   provided by the SamplePathProvider. 
    ' </returns> 
    Public Function GetVirtualData() As DataSet
      ' Get the data from the cache. 
      Dim ds As DataSet
      ds = CType(HostingEnvironment.Cache.Get("VPPData"), DataSet)

      If ds Is Nothing Then 
        ' Data set not in cache. Read XML file.
        ds = New DataSet
        ds.ReadXml(dataFile)

        ' Make DataSet dependent on XML file. 
        Dim cd As CacheDependency
        cd = New CacheDependency(dataFile)

        ' Put DataSet into cache for maximum of 20 minutes.
        HostingEnvironment.Cache.Add("VPPData", ds, cd, _
         Cache.NoAbsoluteExpiration, _
         New TimeSpan(0, 20, 0), _
         CacheItemPriority.Default, Nothing)

        ' Set data timestamp. 
        Dim dataTimeStamp As DateTime
        dataTimeStamp = DateTime.Now
        ' Cache it so we can get the timestamp in later calls.
        HostingEnvironment.Cache.Add("dataTimeStamp", dataTimeStamp, Nothing, _
          Cache.NoAbsoluteExpiration, _
          New TimeSpan(0, 20, 0), _
          CacheItemPriority.Default, Nothing)
      End If 
      Return ds
    End Function 

    Private Function IsPathVirtual(ByVal virtualPath As String) As Boolean 
      Dim checkPath As String
      checkPath = VirtualPathUtility.ToAppRelative(virtualPath)
      Return checkPath.StartsWith("~/vrdir", StringComparison.InvariantCultureIgnoreCase)
    End Function 

    Public Overrides Function FileExists(ByVal virtualPath As String) As Boolean 
      If (IsPathVirtual(virtualPath)) Then 
        Dim file As SampleVirtualFile
        file = CType(GetFile(virtualPath), SampleVirtualFile)
        Return file.Exists
      Else 
        Return Previous.FileExists(virtualPath)
      End If 
    End Function 

    Public Overrides Function DirectoryExists(ByVal virtualDir As String) As Boolean 
      If (IsPathVirtual(virtualDir)) Then 
        Dim dir As SampleVirtualDirectory
        dir = CType(GetDirectory(virtualDir), SampleVirtualDirectory)
        Return dir.exists
      Else 
        Return Previous.DirectoryExists(virtualDir)
      End If 
    End Function 

    Public Overrides Function GetFile(ByVal virtualPath As String) As VirtualFile
      If (IsPathVirtual(virtualPath)) Then 
        Return New SampleVirtualFile(virtualPath, Me)
      Else 
        Return Previous.GetFile(virtualPath)
      End If 
    End Function 

    Public Overrides Function GetDirectory(ByVal virtualDir As String) As VirtualDirectory
      If (IsPathVirtual(virtualDir)) Then 
        Return New SampleVirtualDirectory(virtualDir, Me)
      Else 
        Return Previous.GetDirectory(virtualDir)
      End If 
    End Function 

    Public Overrides Function GetCacheDependency(ByVal virtualPath As String, ByVal virtualPathDependencies As IEnumerable, ByVal utcStart As Date) As CacheDependency
      If (IsPathVirtual(virtualPath)) Then 

        Dim fullPathDependencies As System.Collections.Specialized.StringCollection
        fullPathDependencies = Nothing 

        ' Get the full path to all dependencies. 
        For Each virtualDependency As String In virtualPathDependencies
          If fullPathDependencies Is Nothing Then
            fullPathDependencies = New System.Collections.Specialized.StringCollection
          End If

          fullPathDependencies.Add(virtualDependency)
        Next 

        If fullPathDependencies Is Nothing Then 
          Return Nothing 
        End If 

        Dim fullPathDependenciesArray As String()
        fullPathDependencies.CopyTo(fullPathDependenciesArray, 0)

        Return New CacheDependency(fullPathDependenciesArray, utcStart)
      Else 
        Return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart)
      End If 
    End Function 
  End Class 
End Namespace

The second example is the XML data file used to populate the DataSet object returned by the custom VirtualPathProvider object. This XML data is used to demonstrate using the VirtualPathProvider, VirtualDirectory, and VirtualFile objects to retrieve data from external data and is not intended to represent a production-quality data store.

<?xml version="1.0" encoding="utf-8" ?>
  <resource type="dir" 
    path="/vrDir" 
    parentPath="" 
    content="">
    <resource type="file" 
      path="/vrDir/Level1FileA.vrf"
      parentPath="/vrDir" 
      content="This is the content of file Level1FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level1FileB.vrf"
      parentPath="/vrDir" 
      content="This is the content of file Level1FileB.">
    </resource>
    <resource type="dir" 
      path="/vrDir/Level2DirA" 
      parentPath="/vrDir" 
      content="">
    <resource type="file" 
      path="/vrDir/Level2DirA/Level2FileA.vrf" 
      parentPath="/vrDir/Level2DirA" 
      content="This is the content of file Level2FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level2DirA/Level2FileB.vrf"
      parentPath="/vrDir/Level2DirA" 
      content="This is the content of file Level2FileB.">
    </resource>
  </resource>
  <resource type="dir" 
    path="/vrDir/Level2DirB" 
    parentPath="/vrDir" 
    content="">
    <resource type="file" 
      path="/vrDir/Level2DirB/Level2FileA.vrf" 
      parentPath="/vrDir/Level2DirB" 
      content="This is the content of file Level2FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level2DirB/Level2FileB.vrf"
      parentPath="/vrDir/Level2DirB" 
      content="This is the content of file Level2FileB.">
    </resource>
  </resource>
</resource>

The third example provides an AppStart object that contains an AppInitialize method. This method is called during the initialization of an ASP.NET application to perform any custom initialization required. In this case, it registers the custom VirtualPathProvider object with the ASP.NET build system.

Imports Microsoft.VisualBasic

Imports System.Web.Hosting

Namespace Samples.AspNet.VB

  Public Class AppStart

    Public Shared Sub AppInitialize()
      Dim sampleProvider As SamplePathProvider = New SamplePathProvider()
      HostingEnvironment.RegisterVirtualPathProvider(sampleProvider)
    End Sub 

  End Class 
End Namespace

The last example is an ASP.NET page that contains links to the virtual files contained in the virtual file system.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <meta http-equiv="Content-Type" content="text/html" />
  <title>Virtual Path Provider Example</title>
</head>
<body>
  <form id="form1" runat="server">
    <asp:HyperLink ID="hyperLink1" runat="server" NavigateUrl="vrDir/Level1FileA.vrf" Text="Level 1, File A" /><br />
    <asp:HyperLink ID="hyperLink2" runat="server" NavigateUrl="vrDir/Level1FileB.vrf" Text="Level 1, File B" /><br />
    <asp:HyperLink ID="hyperLink3" runat="server" NavigateUrl="vrDir/Level2DirA/Level2FileA.vrf" Text="Level 2a, File A" /><br />
    <asp:HyperLink ID="hyperLink4" runat="server" NavigateUrl="vrDir/Level2DirA/Level2FileB.vrf" Text="Level 2a, File B" /><br />
    <asp:HyperLink ID="hyperLink5" runat="server" NavigateUrl="vrDir/Level2DirB/Level2FileA.vrf" Text="Level 2b, File A" /><br />
    <asp:HyperLink ID="hyperLink6" runat="server" NavigateUrl="vrDir/Level2DirB/Level2FileB.vrf" Text="Level 2b, File B" /><br />
  </form>
</body>
</html>
System.Object
  System.MarshalByRefObject
    System.Web.Hosting.VirtualPathProvider
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.