VirtualFile 클래스

정의

가상 파일 또는 리소스 공간의 파일 개체를 나타냅니다.

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
상속

예제

다음 코드 예제는 HTML 데이터를 반환 하는 템플릿 파일과 개체에 VirtualFile 저장 된 정보를 결합 하는 클래스 구현입니다DataSet. 이 코드 예제는 개체에 로드되는 데이터 저장소의 가상 리소스를 제공하기 위해 클래스 및 VirtualPathProvider 클래스의 코드 예제 VirtualDirectoryDataSet 함께 작동합니다. 예제를 컴파일하고 실행하기 위한 전체 지침은 클래스 개요의 예제 섹션을 VirtualPathProvider 참조하세요.

이 예제에는 클래스 구현, 개체를 채우는 VirtualFile 데 사용되는 XML 데이터 파일 및 페이지 템플릿 파일의 세 부분이 DataSet 있습니다.

첫 번째 코드 예제는 클래스의 구현입니다 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

두 번째 예제는 사용자 지정 DataSet 개체에서 반환된 개체를 VirtualPathProvider 채우는 데 사용되는 XML 데이터 파일입니다. 이 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>

세 번째 예제는 가상 파일의 템플릿으로 사용되는 텍스트 파일입니다. 파일의 자리 표시자는 백분율(%) 표시(예: 및 %file%) 사이의 텍스트로 %content% 표시됩니다. 타임스탬프는 캐시된 가상 파일 데이터의 변경 내용을 모니터링하는 데 사용됩니다.

<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 는 가상 파일 시스템의 파일을 나타내는 개체의 기본 클래스입니다. 일반적으로 웹 애플리케이션의 각 VirtualFile 개체 하위 항목에 대해 클래스의 VirtualPathProvider 하위 항목을 구현합니다.

구현자 참고

클래스에서 상속하는 VirtualFile 경우 가상 리소스의 콘텐츠에 Open() 읽기 전용 스트림을 반환하도록 메서드를 재정의해야 합니다.

생성자

Name Description
VirtualFile(String)

VirtualFile 클래스의 새 인스턴스를 초기화합니다.

속성

Name Description
IsDirectory

파일로 처리해야 하는 가상 리소스임을 나타내는 값을 가져옵니다.

Name

가상 리소스의 표시 이름을 가져옵니다.

(다음에서 상속됨 VirtualFileBase)
VirtualPath

가상 파일 경로를 가져옵니다.

(다음에서 상속됨 VirtualFileBase)

메서드

Name Description
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)

적용 대상