VirtualPathProvider クラス
アセンブリ: System.Web (system.web.dll 内)


VirtualPathProvider クラスには、Web アプリケーションの仮想ファイル システムを実装するための一連のメソッドが用意されています。仮想ファイル システムでは、サーバーのオペレーティング システムで提供されるファイル システムとは別のデータ ストアでファイルおよびディレクトリが管理されます。たとえば、仮想ファイル システムを使用して、SQL Server データベースの内容を格納できます。
要求に応じて処理される任意のファイルを仮想ファイル システムに格納できます。これには、次のものが含まれます。
アプリケーション レベルのアセンブリを生成する ASP.NET アプリケーション フォルダやファイルは、仮想ファイル システムに格納できません。これには、次のものが含まれます。
-
Global.asax ファイル。
-
Web.config ファイル。
-
アプリケーション アセンブリを格納または生成するディレクトリ。つまり、Bin、App_Code、App_GlobalResources、App_LocalResources の各ディレクトリ。
![]() |
---|
Web サイトが配置のためにプリコンパイルされている場合、VirtualPathProvider インスタンスによって提供される内容はコンパイルされません。プリコンパイル済みサイトでは VirtualPathProvider インスタンスは使用されません。 |
T:System.Web.Hosting.VirtualPathProvider の登録
VirtualPathProvider カスタム インスタンスは、Web アプリケーションによるページ解析とコンパイルの前に、HostingEnvironment.RegisterVirtualPathProvider メソッドを使用して ASP.NET コンパイル システムに登録する必要があります。
通常、VirtualPathProvider インスタンスは、App_Code ディレクトリに定義されている AppInitialize メソッドで登録されるか、または Global.asax ファイルに定義されている Application_Start イベント時に登録されます。AppInitialize メソッドで VirtualPathProvider インスタンスを登録する例については、「例」を参照してください。
他のイベント時に VirtualPathProvider インスタンスを登録できますが、以前にコンパイル済みのページのソースが新しい VirtualPathProvider インスタンスによって提供されても、VirtualPathProvider インスタンスが登録される前にコンパイルおよびキャッシュされたページは無効になりません。
-
FileExists
-
GetFile
-
DirectoryExists
-
GetDirectory
![]() |
---|
App_Themes 仮想 ディレクトリを作成することにより、仮想ファイル システムに Web サイトのテーマを格納する場合は、VirtualPathProvider カスタム クラスでディレクトリをサポートする必要があります。 |

DataSet オブジェクトに格納されている情報を使用して仮想ファイル システムを作成する VirtualPathProvider クラスの実装例を次のコード例に示します。このコード例は、VirtualFile クラスおよび VirtualDirectory クラスのコード例と連携して、DataSet オブジェクトに読み込まれたデータ ストアから仮想リソースを返します。
この例は、4 つの部分で構成されます。最初に VirtualPathProvider クラスの実装例を示します。次に、DataSet オブジェクトを設定するために使用される XML データ ファイルを示します。さらに、VirtualPathProvider クラスをコンパイル システムに登録するために使用される AppInitialize メソッドが定義されている AppStart オブジェクトを示します。最後に、仮想ファイルへのリンクを提供する ASP.NET ページを示します。
このサンプル コードをアプリケーションで使用するには、次の手順を実行します。
-
VirtualPathProvider カスタム オブジェクト (下記を参照) のソース コードを、アプリケーションの App_Code ディレクトリ内にあるファイルにコピーします。
-
VirtualDirectory カスタム オブジェクトのソース コードを、アプリケーションの App_Code ディレクトリ内にあるファイルにコピーします。このソース コードについては、VirtualDirectory クラスの概要のトピックで「例」を参照してください。
-
VirtualFile カスタム オブジェクトのソース コードを、アプリケーションの App_Code ディレクトリ内にあるファイルにコピーします。このソース コードについては、VirtualFile クラスの概要のトピックで「例」を参照してください。
-
AppStart オブジェクトのソース コード (下記を参照) を、アプリケーションの App_Code ディレクトリ内にあるファイルにコピーします。
-
XML データ (下記を参照) をアプリケーションの App_Data ディレクトリ内にある XMLData.xml という名前のファイルにコピーします。
-
default.aspx ファイル (下記を参照) をサンプル アプリケーションのルート ディレクトリにコピーします。Web ブラウザを使用して default.aspx ファイルを開き、ページ上のリンクをクリックして仮想ファイルの内容を表示します。
最初の例は、VirtualPathProvider カスタム クラスです。DirectoryExists メソッドおよび FileExists メソッドをオーバーライドして、要求されたディレクトリが仮想ファイル システム内に存在するかどうかを示します。GetDirectory メソッドおよび GetFile メソッドをオーバーライドして、仮想ファイル システムの情報を格納している VirtualDirectory インスタンスおよび VirtualFile インスタンスを返します。
このクラスは、VirtualDirectory クラスおよび VirtualFile クラスで使用される GetVirtualData メソッドも提供します。これにより、仮想ファイル システムのデータを格納している DataSet オブジェクトにアクセスできるようになります。本番の実装では、このメソッドは、通常、データ ストアと対話するビジネス オブジェクトに実装されます。
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
using System; using System.Data; using System.Security.Permissions; using System.Web; using System.Web.Caching; using System.Web.Hosting; namespace Samples.AspNet.CS { [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.High)] public class SamplePathProvider : VirtualPathProvider { private string dataFile; public SamplePathProvider() : base() { } protected override void Initialize() { // Set the datafile path relative to the application's path. dataFile = HostingEnvironment.ApplicationPhysicalPath + "App_Data\\XMLData.xml"; } /// <summary> /// Data set provider for the SampleVirtualDirectory and /// SampleVirtualFile 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 DataSet GetVirtualData() { // Get the data from the cache. DataSet ds = (DataSet)HostingEnvironment.Cache.Get("VPPData"); if (ds == null) { // Data not in cache. Read XML file. ds = new DataSet(); ds.ReadXml(dataFile); // Make DataSet dependent on XML file. 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, null); // Set data timestamp. DateTime dataTimeStamp = DateTime.Now; // Cache it so we can get the timestamp in later calls. HostingEnvironment.Cache.Insert("dataTimeStamp", dataTimeStamp, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.Default, null); } return ds; } /// <summary> /// Determines whether a specified virtual path is within /// the virtual file system. /// </summary> /// <param name="virtualPath">An absolute virtual path.</param> /// <returns> /// true if the virtual path is within the /// virtual file sytem; otherwise, false. /// </returns> private bool IsPathVirtual(string virtualPath) { String checkPath = VirtualPathUtility.ToAppRelative(virtualPath); return checkPath.StartsWith("~/vrdir", StringComparison.InvariantCultureIgnoreCase); } public override bool FileExists(string virtualPath) { if (IsPathVirtual(virtualPath)) { SampleVirtualFile file = (SampleVirtualFile)GetFile(virtualPath); return file.Exists; } else return Previous.FileExists(virtualPath); } public override bool DirectoryExists(string virtualDir) { if (IsPathVirtual(virtualDir)) { SampleVirtualDirectory dir = (SampleVirtualDirectory)GetDirectory(virtualDir); return dir.Exists; } else return Previous.DirectoryExists(virtualDir); } public override VirtualFile GetFile(string virtualPath) { if (IsPathVirtual(virtualPath)) return new SampleVirtualFile(virtualPath, this); else return Previous.GetFile(virtualPath); } public override VirtualDirectory GetDirectory(string virtualDir) { if (IsPathVirtual(virtualDir)) return new SampleVirtualDirectory(virtualDir, this); else return Previous.GetDirectory(virtualDir); } public override CacheDependency GetCacheDependency( string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart) { if (IsPathVirtual(virtualPath)) { System.Collections.Specialized.StringCollection fullPathDependencies = null; // Get the full path to all dependencies. foreach (string virtualDependency in virtualPathDependencies) { if (fullPathDependencies == null) fullPathDependencies = new System.Collections.Specialized.StringCollection(); fullPathDependencies.Add(virtualDependency); } if (fullPathDependencies == null) return null; // Copy the list of full-path dependencies into an array. string[] fullPathDependenciesArray = new string[fullPathDependencies.Count]; fullPathDependencies.CopyTo(fullPathDependenciesArray, 0); // Copy the virtual path into an array. string[] virtualPathArray = new string[1]; virtualPathArray[0] = virtualPath; return new CacheDependency(virtualPathArray, fullPathDependenciesArray, utcStart); } else return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart); } }
2 番目の例は、VirtualPathProvider カスタム オブジェクトによって返された DataSet オブジェクトを設定するために使用される XML データ ファイルを示しています。この XML データは VirtualPathProvider、VirtualDirectory、および VirtualFile の各オブジェクトを使用して外部データからデータを取得する例を示すものであり、本番品質のデータ ストアを表しているものではありません。
<?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>
3 番目の例では、AppInitialize メソッドが格納されている AppStart オブジェクトを示します。このメソッドは、ASP.NET アプリケーションの初期化時に呼び出され、必要なカスタム初期化処理を実行します。この例では、VirtualPathProvider カスタム オブジェクトを ASP.NET ビルド システムに登録します。
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
using System.Web.Hosting; namespace Samples.AspNet.CS { /// <summary> /// Contains the application initialization method /// for the sample application. /// </summary> public static class AppStart { public static void AppInitialize() { SamplePathProvider sampleProvider = new SamplePathProvider(); HostingEnvironment.RegisterVirtualPathProvider(sampleProvider); } } }
最後の例では、仮想ファイル システムに格納されている仮想ファイルへのリンクを含む ASP.NET ページを示します。
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <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>
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> </script> <html > <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <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.MarshalByRefObject
System.Web.Hosting.VirtualPathProvider


Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


VirtualPathProvider コンストラクタ
アセンブリ: System.Web (system.web.dll 内)


VirtualPathProvider コンストラクタをオーバーライドする場合は、VirtualPathProvider オブジェクトを Initialize メソッドに登録した後で実行する必要のある初期化処理を延期してください。

VirtualPathProvider カスタム クラスを初期化する VirtualPathProvider コンストラクタの実装例を次のコード例に示します。例の実行に必要なコード全体については、VirtualPathProvider クラスの概要のトピックで「例」を参照してください。

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


VirtualPathProvider プロパティ
VirtualPathProvider メソッド


名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | Initialize | VirtualPathProvider インスタンスを初期化します。 |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

VirtualPathProvider メンバ
Web アプリケーションによって仮想ファイル システムのリソースを取得できるようにする一連のメソッドが用意されています。
VirtualPathProvider データ型で公開されるメンバを以下の表に示します。




名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | Initialize | VirtualPathProvider インスタンスを初期化します。 |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

- VirtualPathProviderのページへのリンク