FileSystemInfo FileSystemInfo FileSystemInfo FileSystemInfo Class

Definición

Proporciona la clase base para los objetos FileInfo y DirectoryInfo.Provides the base class for both FileInfo and DirectoryInfo objects.

public ref class FileSystemInfo abstract : MarshalByRefObject, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class FileSystemInfo : MarshalByRefObject, System.Runtime.Serialization.ISerializable
type FileSystemInfo = class
    inherit MarshalByRefObject
    interface ISerializable
Public MustInherit Class FileSystemInfo
Inherits MarshalByRefObject
Implements ISerializable
Herencia
Derivado
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo recorrer en bucle todos los archivos y directorios, consultando información sobre cada entrada.The following example shows how to loop through all the files and directories, querying some information about each entry.

using namespace System;
using namespace System::IO;


namespace ConsoleApplication2
{
    public ref class Program
    {
    public:
        static void Main()
        {
            //  Loop through all the immediate subdirectories of C.
            for each (String^ entry in Directory::GetDirectories("C:\\"))
            {
                DisplayFileSystemInfoAttributes(gcnew DirectoryInfo(entry));
            }
            //  Loop through all the files in C.
            for each (String^ entry in Directory::GetFiles("C:\\"))
            {
                DisplayFileSystemInfoAttributes(gcnew FileInfo(entry));
            }
        }
        static void DisplayFileSystemInfoAttributes(FileSystemInfo^ fsi)
        {
            //  Assume that this entry is a file.
            String^ entryType = "File";

            // Determine if entry is really a directory
            if ((fsi->Attributes & FileAttributes::Directory) == FileAttributes::Directory)
            {
                entryType = "Directory";
            }
            //  Show this entry's type, name, and creation date.
            Console::WriteLine("{0} entry {1} was created on {2:D}", entryType, fsi->FullName, fsi->CreationTime);
        }
    };
};

int main()
{
    ConsoleApplication2::Program::Main();
}

 // Output will vary based on contents of drive C.

 // Directory entry C:\Documents and Settings was created on Tuesday, November 25, 2003
 // Directory entry C:\Inetpub was created on Monday, January 12, 2004
 // Directory entry C:\Program Files was created on Tuesday, November 25, 2003
 // Directory entry C:\RECYCLER was created on Tuesday, November 25, 2003
 // Directory entry C:\System Volume Information was created on Tuesday, November 2, 2003
 // Directory entry C:\WINDOWS was created on Tuesday, November 25, 2003
 // File entry C:\IO.SYS was created on Tuesday, November 25, 2003
 // File entry C:\MSDOS.SYS was created on Tuesday, November 25, 2003
 // File entry C:\pagefile.sys was created on Saturday, December 27, 2003
using System;
using System.IO;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //  Loop through all the immediate subdirectories of C.
            foreach (string entry in Directory.GetDirectories(@"C:\"))
            {
                DisplayFileSystemInfoAttributes(new DirectoryInfo(entry));
            }
            //  Loop through all the files in C.
            foreach (string entry in Directory.GetFiles(@"C:\"))
            {
                DisplayFileSystemInfoAttributes(new FileInfo(entry));
            }
        }
        static void DisplayFileSystemInfoAttributes(FileSystemInfo fsi)
        {
            //  Assume that this entry is a file.
            string entryType = "File";

            // Determine if entry is really a directory
            if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory )
            {
                entryType = "Directory";
            }
            //  Show this entry's type, name, and creation date.
            Console.WriteLine("{0} entry {1} was created on {2:D}", entryType, fsi.FullName, fsi.CreationTime);
        }
    }
}

 // Output will vary based on contents of drive C.
 
 // Directory entry C:\Documents and Settings was created on Tuesday, November 25, 2003
 // Directory entry C:\Inetpub was created on Monday, January 12, 2004
 // Directory entry C:\Program Files was created on Tuesday, November 25, 2003
 // Directory entry C:\RECYCLER was created on Tuesday, November 25, 2003
 // Directory entry C:\System Volume Information was created on Tuesday, November 2, 2003
 // Directory entry C:\WINDOWS was created on Tuesday, November 25, 2003
 // File entry C:\IO.SYS was created on Tuesday, November 25, 2003
 // File entry C:\MSDOS.SYS was created on Tuesday, November 25, 2003
 // File entry C:\pagefile.sys was created on Saturday, December 27, 2003
Imports System.IO
Module Module1

    Sub Main()
        ' Loop through all the immediate subdirectories of C.
        For Each entry As String In Directory.GetDirectories("C:\")
            DisplayFileSystemInfoAttributes(New DirectoryInfo(entry))
        Next

        ' Loop through all the files in C.
        For Each entry As String In Directory.GetFiles("C:\")
            DisplayFileSystemInfoAttributes(New FileInfo(entry))
        Next
    End Sub

    Sub DisplayFileSystemInfoAttributes(ByVal fsi As IO.FileSystemInfo)
        ' Assume that this entry is a file.
        Dim entryType As String = "File"

        ' Determine if this entry is really a directory.
        If (fsi.Attributes And FileAttributes.Directory) = FileAttributes.Directory Then
            entryType = "Directory"
        End If

        ' Show this entry's type, name, and creation date.
        Console.WriteLine("{0} entry {1} was created on {2:D}", _
            entryType, fsi.FullName, fsi.CreationTime)
    End Sub
End Module

' Output will vary based on contents of drive C.
' 
' Directory entry C:\Documents and Settings was created on Tuesday, November 25, 2003
' Directory entry C:\Inetpub was created on Monday, January 12, 2004
' Directory entry C:\Program Files was created on Tuesday, November 25, 2003
' Directory entry C:\RECYCLER was created on Tuesday, November 25, 2003
' Directory entry C:\System Volume Information was created on Tuesday, November 2, 2003
' Directory entry C:\WINDOWS was created on Tuesday, November 25, 2003
' File entry C:\IO.SYS was created on Tuesday, November 25, 2003
' File entry C:\MSDOS.SYS was created on Tuesday, November 25, 2003
' File entry C:\pagefile.sys was created on Saturday, December 27, 2003

Comentarios

La FileSystemInfo clase contiene métodos que son comunes a la manipulación de archivos y directorios.The FileSystemInfo class contains methods that are common to file and directory manipulation. Un FileSystemInfo objeto puede representar un archivo o un directorio, y, por tanto, servir como FileInfo base DirectoryInfo para los objetos o.A FileSystemInfo object can represent either a file or a directory, thus serving as the basis for FileInfo or DirectoryInfo objects. Use esta clase base al analizar una gran cantidad de archivos y directorios.Use this base class when parsing a lot of files and directories.

Una clase derivada solo puede heredar de FileSystemInfo si la clase derivada tiene el permiso AllAccess de la FileIOPermissionAccess enumeración.A derived class can inherit from FileSystemInfo only if the derived class has the AllAccess permission from the FileIOPermissionAccess enumeration.

En los miembros que aceptan una ruta de acceso, la ruta de acceso puede hacer referencia a un archivo o solo a un directorio.In members that accept a path, the path can refer to a file or just a directory. La ruta de acceso especificada también puede hacer referencia a una ruta de acceso relativa o a una ruta de acceso UNC (Convención de nomenclatura universal) para un servidor y un nombre de recurso compartido.The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. Por ejemplo, todas las siguientes son rutas de acceso aceptables:For example, all the following are acceptable paths:

  • "c:\\MyDir\\MyFile.txt" in C#o "c:\MyDir\MyFile.txt" en Visual Basic."c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • "c:\\MyDir" in C#o "c:\MiDir" en Visual Basic."c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • "MyDir\\MySubdir" in C#o "MyDir\MySubDir" en Visual Basic."MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • "\\ C#\MyServer \MyShare" in o"\\miservidor\mirecursocompartido" en Visual Basic.\\"\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

Para obtener una lista de tareas de e/s comunes, consulte tareas comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Constructores

FileSystemInfo() FileSystemInfo() FileSystemInfo() FileSystemInfo()

Inicializa una nueva instancia de la clase FileSystemInfo.Initializes a new instance of the FileSystemInfo class.

FileSystemInfo(SerializationInfo, StreamingContext) FileSystemInfo(SerializationInfo, StreamingContext) FileSystemInfo(SerializationInfo, StreamingContext) FileSystemInfo(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase FileSystemInfo con datos serializados.Initializes a new instance of the FileSystemInfo class with serialized data.

Campos

FullPath FullPath FullPath FullPath

Representa la ruta de acceso completa del directorio o el archivo.Represents the fully qualified path of the directory or file.

OriginalPath OriginalPath OriginalPath OriginalPath

La ruta de acceso especificada originalmente por el usuario, ya sea relativa o absoluta.The path originally specified by the user, whether relative or absolute.

Propiedades

Attributes Attributes Attributes Attributes

Obtiene o establece los atributos del archivo o directorio actual.Gets or sets the attributes for the current file or directory.

CreationTime CreationTime CreationTime CreationTime

Obtiene o establece la hora de creación del archivo o directorio actual.Gets or sets the creation time of the current file or directory.

CreationTimeUtc CreationTimeUtc CreationTimeUtc CreationTimeUtc

Obtiene o establece la hora de creación, en formato de hora universal coordinada (UTC), del archivo o directorio actual.Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

Exists Exists Exists Exists

Obtiene un valor que indica si existe el archivo o directorio.Gets a value indicating whether the file or directory exists.

Extension Extension Extension Extension

Obtiene la cadena que representa la extensión del archivo.Gets the string representing the extension part of the file.

FullName FullName FullName FullName

Obtiene la ruta de acceso completa del directorio o el archivo.Gets the full path of the directory or file.

LastAccessTime LastAccessTime LastAccessTime LastAccessTime

Obtiene o establece la hora en la que se utilizó por última vez el archivo o directorio actual.Gets or sets the time the current file or directory was last accessed.

LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc

Obtiene o establece la hora, en formato de hora universal coordinada (UTC), a la que se produjo el último acceso al archivo o directorio actual.Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

LastWriteTime LastWriteTime LastWriteTime LastWriteTime

Obtiene o establece la hora en la que se escribió por última vez en el archivo o directorio actual.Gets or sets the time when the current file or directory was last written to.

LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc

Obtiene o establece la hora, en formato de hora universal coordinada (UTC), a la que se escribió por última vez en el archivo o directorio actual.Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

Name Name Name Name

Para archivos, obtiene el nombre del archivo.For files, gets the name of the file. Para directorios, obtiene el nombre del último directorio de la jerarquía, si existe tal jerarquía.For directories, gets the name of the last directory in the hierarchy if a hierarchy exists. De lo contrario, la propiedad Name obtiene el nombre del directorio.Otherwise, the Name property gets the name of the directory.

Métodos

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Delete() Delete() Delete() Delete()

Elimina un archivo o directorio.Deletes a file or directory.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Establece el objeto SerializationInfo con el nombre del archivo y la información adicional de la excepción.Sets the SerializationInfo object with the file name and additional exception information.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Refresh() Refresh() Refresh() Refresh()

Actualiza el estado del objeto.Refreshes the state of the object.

ToString() ToString() ToString() ToString()

Devuelve la ruta de acceso original.Returns the original path. Use las propiedades FullName o Name para la ruta de acceso completa o el nombre de archivo o directorio.Use the FullName or Name properties for the full path or file/directory name.

Seguridad

FileIOPermission
permiso para heredar de esta clase.for permission to inherit from this class. Enumeración asociada:UnrestrictedAssociated enumeration: Unrestricted Acción de seguridad: Petición de herenciaSecurity Action: Inheritance Demand

Se aplica a

Consulte también: