VirtualDirectory Classe

Definizione

Rappresenta un oggetto directory in un file virtuale o nello spazio delle risorse.

public ref class VirtualDirectory abstract : System::Web::Hosting::VirtualFileBase
public abstract class VirtualDirectory : System.Web.Hosting.VirtualFileBase
type VirtualDirectory = class
    inherit VirtualFileBase
Public MustInherit Class VirtualDirectory
Inherits VirtualFileBase
Ereditarietà

Esempio

L'esempio di codice seguente è un'implementazione della VirtualDirectory classe che restituisce informazioni sulla directory virtuale archiviate in un DataSet oggetto . Questo codice funziona con gli esempi di codice per le VirtualPathProvider classi e VirtualFile per fornire risorse virtuali da un archivio dati caricato in un DataSet oggetto . Per le istruzioni complete per la compilazione e l'esecuzione dell'esempio, vedere la sezione Esempio della panoramica della VirtualPathProvider classe.

In questo esempio sono presenti due parti, l'implementazione della VirtualDirectory classe e il file di dati XML usato per popolare l'oggetto DataSet .

Il primo esempio di codice è un'implementazione della VirtualDirectory classe . Nel costruttore usa un metodo su un oggetto personalizzato VirtualPathProvider per restituire un DataSet oggetto . Esegue quindi la ricerca nell'oggetto DataSet per recuperare le informazioni sulla directory associate al percorso virtuale specificato.

using System;
using System.Collections;
using System.Data;
using System.Security.Permissions;
using System.Web;
using System.Web.Hosting;

namespace Samples.AspNet.CS
{
  [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  public class SampleVirtualDirectory : VirtualDirectory
  {
    SamplePathProvider spp;

    private bool exists;
    public bool Exists
    {
      get { return exists; }
    }

    public SampleVirtualDirectory(string virtualDir, SamplePathProvider provider)
      : base(virtualDir)
    {
      spp = provider;
      GetData();
    }

    protected void GetData()
    {
      DataSet ds = spp.GetVirtualData();

      // Clean up the path to match data in resource file.
      string path = VirtualPath.Replace(HostingEnvironment.ApplicationVirtualPath, "");
      path = path.TrimEnd('/');

      // Get the virtual directory from the resource table.
      DataTable dirs = ds.Tables["resource"];
      DataRow[] rows = dirs.Select(
        String.Format("(name = '{0}') AND (type='dir')", path));

      // If the select returned a row, the directory exists.
      if (rows.Length > 0)
      {
        exists = true;

        // Get children from the resource table.
        // This technique works for small numbers of virtual resources.
        //   Sites with moderate to large numbers of virtual
        //   resources should choose a method that consumes fewer
        //   computer resources.
        DataRow[] childRows = dirs.Select(
          String.Format("parentPath = '{0}'", path));

        foreach (DataRow childRow in childRows)
        {
          string childPath = (string)childRow["path"];

          if (childRow["type"].ToString() == "dir")
          {
            SampleVirtualDirectory svd = new SampleVirtualDirectory(childPath, spp);
            children.Add(svd);
            directories.Add(svd);
          }
          else
          {
            SampleVirtualFile svf = new SampleVirtualFile(childPath, spp);
            children.Add(svf);
            files.Add(svf);
          }
        }
      }
    }

    private ArrayList children = new ArrayList();
    public override IEnumerable Children
    {
      get { return children; }
    }

    private ArrayList directories = new ArrayList();
    public override IEnumerable Directories
    {
      get { return directories; }
    }

    private ArrayList files = new ArrayList();
    public override IEnumerable Files
    {
      get { return files; }
    }
  }
}

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


Namespace Samples.AspNet.VB
  <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal), _
   AspNetHostingPermission(SecurityAction.InheritanceDemand, level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class SampleVirtualDirectory
    Inherits VirtualDirectory

    Private spp As SamplePathProvider

    ' Declare the variable the property uses.
    Private existsValue As Boolean

    Public ReadOnly Property exists() As Boolean
      Get
        Return existsValue
      End Get
    End Property

    Public Sub New(ByVal virtualDir As String, ByVal provider As SamplePathProvider)
      MyBase.New(virtualDir)
      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

      ' Clean up the path to match data in resource file.
      Dim path As String
      path = VirtualPath.Replace(HostingEnvironment.ApplicationVirtualPath, "")
      Dim trimChars() As Char = {"/"c}
      path = path.TrimEnd(trimChars)

      ' Get the virtual directory from the resource table.
      Dim dirs As DataTable
      dirs = ds.Tables("resource")
      Dim rows As DataRow()
      rows = dirs.Select( _
        String.Format("(name = '{0}') AND (type='dir')", path))

      ' If the select returned a row, the directory exits.
      If (rows.Length > 0) Then
        existsValue = True

        ' Get the children from the resource table.
        ' This technique works for small numbers of virtual resources.
        '  Sites with moderate to large numbers of virtual
        '  resources should choose a method that consumes fewer
        '  computer resources.
        Dim childRows As DataRow()
        childRows = dirs.Select( _
          String.Format("parentPath = '{0}'", path))

        For Each childRow As DataRow In childRows
          Dim childPath As String
          childPath = CType(childRow("path"), String)

          If (childRow("type").ToString = "dir") Then
            Dim svd As New SampleVirtualDirectory(childPath, spp)
            childrenValue.Add(svd)
            directoriesValue.Add(svd)
          Else
            Dim svf As New SampleVirtualFile(childPath, spp)
            childrenValue.Add(svf)
            directoriesValue.Add(svf)
          End If
        Next

      End If
    End Sub

    Private childrenValue As ArrayList
    Public Overrides ReadOnly Property Children() As System.Collections.IEnumerable
      Get
        Return childrenValue
      End Get
    End Property

    Private directoriesValue As ArrayList
    Public Overrides ReadOnly Property Directories() As System.Collections.IEnumerable
      Get
        Return directoriesValue
      End Get
    End Property

    Private filesValue As ArrayList
    Public Overrides ReadOnly Property Files() As System.Collections.IEnumerable
      Get
        Return filesValue
      End Get
    End Property
  End Class

End Namespace

Il secondo esempio è il file di dati XML utilizzato per popolare l'oggetto DataSet restituito dall'oggetto personalizzato VirtualPathProvider . Questi dati XML vengono usati per illustrare l'uso delle VirtualPathProviderclassi , VirtualFilee VirtualDirectory per recuperare dati da dati esterni e non rappresentano un archivio dati di qualità di produzione.

<?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>  

Commenti

La VirtualDirectory classe è la classe base per gli oggetti che rappresentano le directory in un file system virtuale. In genere, si implementa un discendente della VirtualDirectory classe per ogni VirtualPathProvider discendente di classe nell'applicazione Web.

Note per gli implementatori

Quando si eredita dalla VirtualDirectory classe , è necessario eseguire l'override delle Childrenproprietà , Directoriese Files per restituire un oggetto che implementa l'interfaccia IEnumerable .

Se la struttura di directory virtuale contiene un numero moderato o elevato di risorse virtuali, è consigliabile ridurre al minimo le risorse di sistema utilizzate durante l'enumerazione della directory virtuale chiamando le Childrenproprietà , Directorieso Files .

Costruttori

VirtualDirectory(String)

Inizializza una nuova istanza della classe VirtualDirectory.

Proprietà

Children

Ottiene un elenco dei file e delle sottodirectory contenute in questa directory virtuale.

Directories

Ottiene un elenco di tutte le sottodirectory contenute in questa directory.

Files

Ottiene un elenco di tutti i file contenuti in questa directory.

IsDirectory

Ottiene un valore che indica che si tratta di una risorsa virtuale che deve essere considerata come una directory.

Name

Ottiene il nome visualizzato della risorsa virtuale.

(Ereditato da VirtualFileBase)
VirtualPath

Ottiene il percorso del file virtuale.

(Ereditato da VirtualFileBase)

Metodi

CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()

Fornisce a un'istanza VirtualFileBase una durata infinita impedendo la creazione di lease.

(Ereditato da VirtualFileBase)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche