FileInfo.Exists Propriedade

Definição

Recebe um valor que indica se um ficheiro 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 de Propriedade

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

Exemplos

O exemplo de código seguinte utiliza a Exists propriedade garantir que existe um ficheiro antes de o abrir. Pode usar esta técnica para lançar uma exceção personalizada quando o ficheiro 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

Observações

Quando é chamado pela primeira vez, FileInfo chama Refresh e armazena em cache informações sobre o ficheiro. Nas chamadas seguintes, deve ligar Refresh para obter a cópia mais recente da informação.

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

Aplica-se a

Ver também