FileSystemInfo Classe

Definição

Fornece a classe base para os objetos FileInfo e 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
Herança
FileSystemInfo
Derivado
Atributos
Implementações

Exemplos

O exemplo a seguir mostra como executar um loop em todos os arquivos e diretórios, consultando algumas informações 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

Comentários

A classe FileSystemInfo contém métodos comuns à manipulação de arquivos e diretórios.The FileSystemInfo class contains methods that are common to file and directory manipulation. Um objeto FileSystemInfo pode representar um arquivo ou um diretório, servindo assim como a base para FileInfo ou DirectoryInfo objetos.A FileSystemInfo object can represent either a file or a directory, thus serving as the basis for FileInfo or DirectoryInfo objects. Use essa classe base ao analisar muitos arquivos e diretórios.Use this base class when parsing a lot of files and directories.

Uma classe derivada pode herdar de FileSystemInfo somente se a classe derivada tiver a permissão de acesso da enumeração FileIOPermissionAccess.A derived class can inherit from FileSystemInfo only if the derived class has the AllAccess permission from the FileIOPermissionAccess enumeration.

Em membros que aceitam um caminho, o caminho pode se referir a um arquivo ou apenas a um diretório.In members that accept a path, the path can refer to a file or just a directory. O caminho especificado também pode se referir a um caminho relativo ou a um caminho UNC (Convenção de nomenclatura universal) para um servidor e um nome de compartilhamento.The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. Por exemplo, todos os seguintes são caminhos aceitáveis:For example, all the following are acceptable paths:

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

  • "c:\\MyDir" em C#ou "c:\MyDir" em Visual Basic."c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • "MyDir\\MySubdir" C#ou "MyDir\MySubDir" em Visual Basic."MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • "\\\\MyServer\\MyShare" in C#, ou "\\meuservidor\meucompartilhamento" em Visual Basic."\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Construtores

FileSystemInfo()

Inicializa uma nova instância da classe FileSystemInfo.Initializes a new instance of the FileSystemInfo class.

FileSystemInfo(SerializationInfo, StreamingContext)

Inicializa uma nova instância da classe FileSystemInfo com dados serializados.Initializes a new instance of the FileSystemInfo class with serialized data.

Campos

FullPath

Representa o caminho totalmente qualificado do diretório ou arquivo.Represents the fully qualified path of the directory or file.

OriginalPath

O caminho originalmente especificado pelo usuário, seja ele relativo ou absoluto.The path originally specified by the user, whether relative or absolute.

Propriedades

Attributes

Obtém ou define os atributos para o arquivo ou diretório atual.Gets or sets the attributes for the current file or directory.

CreationTime

Obtém ou define a hora de criação do arquivo ou diretório atual.Gets or sets the creation time of the current file or directory.

CreationTimeUtc

Obtém ou define a hora de criação, em UTC (tempo universal coordenado), do arquivo ou diretório atual.Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

Exists

Obtém um valor que indica se o arquivo ou o diretório existe.Gets a value indicating whether the file or directory exists.

Extension

Obtém a cadeia de caracteres que representa a parte da extensão do arquivo.Gets the string representing the extension part of the file.

FullName

Obtém o caminho completo do diretório ou arquivo.Gets the full path of the directory or file.

LastAccessTime

Obtém ou define a hora em que o arquivo ou o diretório atual foi acessado pela última vez.Gets or sets the time the current file or directory was last accessed.

LastAccessTimeUtc

Obtém ou define a hora, no UTC (Tempo Universal Coordenado), em que o arquivo ou diretório atual foi acessado pela última vez.Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

LastWriteTime

Obtém ou define a hora em que o arquivo ou o diretório atual foi usado para gravação pela última vez.Gets or sets the time when the current file or directory was last written to.

LastWriteTimeUtc

Obtém ou define a hora, em UTC (Tempo Universal Coordenado), em que o arquivo ou diretório atual foi gravado pela última vez.Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

Name

Para arquivos, obtém o nome do arquivo.For files, gets the name of the file. Para diretórios, obtém o nome do último diretório na hierarquia, se uma existir.For directories, gets the name of the last directory in the hierarchy if a hierarchy exists. Caso contrário, a propriedade Name obtém o nome do diretório.Otherwise, the Name property gets the name of the directory.

Métodos

CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Herdado de MarshalByRefObject)
Delete()

Exclui um arquivo ou diretório.Deletes a file or directory.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

Define o objeto SerializationInfo com o nome do arquivo e informações adicionais de exceção.Sets the SerializationInfo object with the file name and additional exception information.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Herdado de MarshalByRefObject)
Refresh()

Atualiza o estado do objeto.Refreshes the state of the object.

ToString()

Retorna o caminho original.Returns the original path. Use as propriedades FullName ou Name para o caminho completo ou o nome do arquivo/do diretório.Use the FullName or Name properties for the full path or file/directory name.

Segurança

FileIOPermission
para permissão para herdar desta classe.for permission to inherit from this class. Enumeração associada: UnrestrictedAssociated enumeration: Unrestricted Ação de segurança: demanda de herançaSecurity Action: Inheritance Demand

Aplica-se a

Veja também