Compartilhar via


FileInfo.Exists Propriedade

Definição

Obtém um valor que indica se um arquivo existe.

public:
 virtual property bool Exists { bool get(); };
public override bool Exists { get; }
member this.Exists : bool
Public Overrides ReadOnly Property Exists As Boolean

Valor da propriedade

true se o arquivo existir; false se o arquivo não existir ou se o arquivo for um diretório.

Exemplos

O exemplo de código a seguir usa a Exists propriedade para garantir que um arquivo exista antes de abri-lo. Você pode usar essa técnica para gerar uma exceção personalizada quando o arquivo não for encontrado.

public byte[] OpenDataFile(string FileName)
{
    // Check the FileName argument.
    if (FileName == null || FileName.Length == 0)
    {
        throw new ArgumentNullException("FileName");
    }

    // Check to see if the file exists.
    FileInfo fInfo = new FileInfo(FileName);

    // You can throw a personalized exception if
    // the file does not exist.
    if (!fInfo.Exists)
    {
        throw new FileNotFoundException("The file was not found.", FileName);
    }

    // Open the file.
    FileStream fStream = new FileStream(FileName, FileMode.Open);

    // Create a buffer.
    byte [] buffer = new byte[fStream.Length];

    // Read the file contents to the buffer.
    fStream.Read(buffer, 0, (int)fStream.Length);

    // return the buffer.
    return buffer;
}
Function OpenDataFile(ByVal FileName As String) As Byte()
    ' Check the FileName argument.
    If FileName Is Nothing OrElse FileName.Length = 0 Then
        Throw New ArgumentNullException("FileName")
    End If

    ' Check to see if the file exists.
    Dim fInfo As New FileInfo(FileName)

    ' You can throw a personalized exception if 
    ' the file does not exist.
    If Not fInfo.Exists Then
        Throw New FileNotFoundException("The file was not found.", FileName)
    End If

    ' Open the file.
    Dim fStream As New FileStream(FileName, FileMode.Open)

    ' Create a buffer.
    Dim buffer(fStream.Length) As Byte

    ' Read the file contents to the buffer.
    fStream.Read(buffer, 0, Fix(fStream.Length))

    ' return the buffer.
    Return buffer

End Function

Comentários

Quando chamado pela primeira vez, FileInfo chama Refresh e armazena em cache informações sobre o arquivo. Nas chamadas subsequentes, você deve ligar Refresh para obter a cópia mais recente das informações.

A Exists propriedade retornará false se ocorrer algum erro ao tentar determinar se o arquivo especificado existe. Isso pode ocorrer em situações que geram exceções, como passar um nome de arquivo com caracteres inválidos ou muitos caracteres, um disco ausente ou com falha ou se o chamador não tiver permissão para ler o arquivo.

Aplica-se a

Confira também