VirtualFile 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示虚拟文件或资源空间中的一个文件对象。
public ref class VirtualFile abstract : System::Web::Hosting::VirtualFileBase
public abstract class VirtualFile : System.Web.Hosting.VirtualFileBase
type VirtualFile = class
inherit VirtualFileBase
Public MustInherit Class VirtualFile
Inherits VirtualFileBase
- 继承
示例
下面的代码示例是一个 VirtualFile 类实现,它将存储在对象中 DataSet 的信息与模板文件相结合以返回 HTML 数据。 此代码示例适用于 VirtualPathProvider 这些示例和 VirtualDirectory 类,以便从加载到 DataSet 对象的数据存储中提供虚拟资源。 有关编译和运行示例的完整说明,请参阅类概述的 VirtualPathProvider “示例”部分。
此示例包含三个部分: VirtualFile 类实现、用于填充 DataSet 对象的 XML 数据文件和页面模板文件。
第一个代码示例是类的 VirtualFile 实现。 它的构造函数在自定义 VirtualPathProvider 对象上使用方法返回对象 DataSet 。 然后, DataSet 它会搜索对象以检索与提供的虚拟文件路径关联的信息。 在方法中 Open ,它将对象中的信息 DataSet 与模板文件相结合,并将组合作为 Stream 对象返回。
using System;
using System.Data;
using System.IO;
using System.Security.Permissions;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
namespace Samples.AspNet.CS
{
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class SampleVirtualFile : VirtualFile
{
private string content;
private SamplePathProvider spp;
public bool Exists
{
get { return (content != null); }
}
public SampleVirtualFile(string virtualPath, SamplePathProvider provider)
: base(virtualPath)
{
this.spp = provider;
GetData();
}
protected void GetData()
{
// Get the data from the SamplePathProvider
DataSet ds = spp.GetVirtualData();
// Get the virtual file from the resource table.
DataTable files = ds.Tables["resource"];
DataRow[] rows = files.Select(
String.Format("(name = '{0}') AND (type='file')", this.Name));
// If the select returned a row, store the file contents.
if (rows.Length > 0)
{
DataRow row = rows[0];
content = row["content"].ToString();
}
}
private string FormatTimeStamp(DateTime time)
{
return String.Format("{0} at {1}",
time.ToLongDateString(), time.ToLongTimeString());
}
public override Stream Open()
{
string templateFile = HostingEnvironment.ApplicationPhysicalPath + "App_Data\\template.txt";
string pageTemplate;
DateTime now = DateTime.Now;
// Try to get the page template out of the cache.
pageTemplate = (string)HostingEnvironment.Cache.Get("pageTemplate");
if (pageTemplate == null)
{
// Get the page template.
using (StreamReader reader = new StreamReader(templateFile))
{
pageTemplate = reader.ReadToEnd();
}
// Set template timestamp
pageTemplate = pageTemplate.Replace("%templateTimestamp%",
FormatTimeStamp(now));
// Make pageTemplate dependent on the template file.
CacheDependency cd = new CacheDependency(templateFile);
// Put pageTemplate into cache for maximum of 20 minutes.
HostingEnvironment.Cache.Add("pageTemplate", pageTemplate, cd,
Cache.NoAbsoluteExpiration,
new TimeSpan(0, 20, 0),
CacheItemPriority.Default, null);
}
// Put the page data into the template.
pageTemplate = pageTemplate.Replace("%file%", this.Name);
pageTemplate = pageTemplate.Replace("%content%", content);
// Get the data time stamp from the cache.
DateTime dataTimeStamp = (DateTime)HostingEnvironment.Cache.Get("dataTimeStamp");
pageTemplate = pageTemplate.Replace("%dataTimestamp%",
FormatTimeStamp(dataTimeStamp));
pageTemplate = pageTemplate.Replace("%pageTimestamp%",
FormatTimeStamp(now));
// Put the page content on the stream.
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(pageTemplate);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
}
}
Imports System.Data
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.Caching
Imports System.Web.Hosting
Namespace Samples.AspNet.VB
<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class SampleVirtualFile
Inherits VirtualFile
Private content As String
Private spp As SamplePathProvider
Public ReadOnly Property Exists() As Boolean
Get
Return (content <> String.Empty)
End Get
End Property
Public Sub New(ByVal virtualPath As String, ByVal provider As SamplePathProvider)
MyBase.New(virtualPath)
spp = provider
GetData()
End Sub
Protected Sub GetData()
' Get the data from the SamplePathProvider.
Dim spp As SamplePathProvider
spp = CType(HostingEnvironment.VirtualPathProvider, SamplePathProvider)
Dim ds As DataSet
ds = spp.GetVirtualData
' Get the virtual file data from the resource table.
Dim files As DataTable
files = ds.Tables("resource")
Dim rows As DataRow()
rows = files.Select( _
String.Format("(name='{0}') AND (type='file')", Me.Name))
' If the select returned a row, store the file contents.
If (rows.Length > 0) Then
Dim row As DataRow
row = rows(0)
content = row("content").ToString()
End If
End Sub
Private Function FormatTimeStamp(ByVal time As DateTime) As String
Return String.Format("{0} at {1}", _
time.ToLongDateString(), time.ToLongTimeString)
End Function
Public Overrides Function Open() As System.IO.Stream
Dim templateFile As String
templateFile = HostingEnvironment.ApplicationPhysicalPath & "App_Data\template.txt"
Dim pageTemplate As String
Dim now As DateTime
now = DateTime.Now
' Try to get the page template out of the cache.
pageTemplate = CType(HostingEnvironment.Cache.Get("pageTemplate"), String)
If pageTemplate Is Nothing Then
' Get the page template.
Try
pageTemplate = My.Computer.FileSystem.ReadAllText(templateFile)
Catch fileException As Exception
Throw fileException
End Try
' Set template timestamp.
pageTemplate = pageTemplate.Replace("%templateTimestamp%", _
FormatTimeStamp(Now))
' Make pageTemplate dependent on the template file.
Dim cd As CacheDependency
cd = New CacheDependency(templateFile)
' Put pageTemplate into cache for maximum of 20 minutes.
HostingEnvironment.Cache.Add("pageTemplate", pageTemplate, cd, _
Cache.NoAbsoluteExpiration, _
New TimeSpan(0, 20, 0), _
CacheItemPriority.Default, Nothing)
End If
' Put the page data into the template.
pageTemplate = pageTemplate.Replace("%file%", Me.Name)
pageTemplate = pageTemplate.Replace("%content%", content)
' Get the data timestamp from the cache.
Dim dataTimeStamp As DateTime
dataTimeStamp = CType(HostingEnvironment.Cache.Get("dataTimeStamp"), DateTime)
pageTemplate = pageTemplate.Replace("%dataTimestamp%", _
FormatTimeStamp(dataTimeStamp))
' Set a timestamp for the page.
Dim pageTimeStamp As String
pageTimeStamp = FormatTimeStamp(now)
pageTemplate = pageTemplate.Replace("%pageTimestamp%", pageTimeStamp)
' Put the page content on the stream.
Dim stream As MemoryStream
stream = New MemoryStream()
Dim writer As StreamWriter
writer = New StreamWriter(stream)
writer.Write(pageTemplate)
writer.Flush()
stream.Seek(0, SeekOrigin.Begin)
Return stream
End Function
End Class
End Namespace
第二个示例是 XML 数据文件,用于填充 DataSet 自定义 VirtualPathProvider 对象返回的对象。 此 XML 数据用于演示如何使用VirtualPathProvider和VirtualFileVirtualDirectory类从外部数据检索数据,并且不用于表示生产质量的数据存储。
<?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>
第三个示例是用作虚拟文件的模板的文本文件。 文件中的占位符由百分比 (%) 标记(如和%content%
)%file%
之间的文本表示。 时间戳用于监视对缓存虚拟文件数据的更改。
<html>
<head>
<title>File name: %file%</title>
</head>
<body>
<h1>%file%</h1>
<p>%content%</p>
<p>Page timestamp: %pageTimestamp%<br>
Data timestamp: %dataTimestamp%<br>
Template timestamp: %templateTimestamp%</p>
</body>
</html>
注解
该 VirtualFile 类是表示虚拟文件系统中文件的对象的基类。 通常,将为 Web 应用程序中的每个VirtualPathProvider对象后代实现类的VirtualFile子代。
实施者说明
从 VirtualFile 类继承时,必须重写 Open() 该方法以将只读流返回到虚拟资源的内容。
构造函数
VirtualFile(String) |
初始化 VirtualFile 类的新实例。 |
属性
IsDirectory |
获取一个值,该值指示该资源是应作为文件处理的虚拟资源。 |
Name |
获取虚拟资源的显示名称。 (继承自 VirtualFileBase) |
VirtualPath |
获取虚拟文件路径。 (继承自 VirtualFileBase) |
方法
CreateObjRef(Type) |
创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 (继承自 MarshalByRefObject) |
Equals(Object) |
确定指定对象是否等于当前对象。 (继承自 Object) |
GetHashCode() |
作为默认哈希函数。 (继承自 Object) |
GetLifetimeService() |
已过时。
检索控制此实例的生存期策略的当前生存期服务对象。 (继承自 MarshalByRefObject) |
GetType() |
获取当前实例的 Type。 (继承自 Object) |
InitializeLifetimeService() |
通过禁止创建租约来给予 VirtualFileBase 实例无限的生存期。 (继承自 VirtualFileBase) |
MemberwiseClone() |
创建当前 Object 的浅表副本。 (继承自 Object) |
MemberwiseClone(Boolean) |
创建当前 MarshalByRefObject 对象的浅表副本。 (继承自 MarshalByRefObject) |
Open() |
在派生类中重写时,返回到虚拟资源的只读流。 |
ToString() |
返回表示当前对象的字符串。 (继承自 Object) |