FileInfo.Exists Proprietà
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Ottiene un valore che indica se esiste un file.
public:
virtual property bool Exists { bool get(); };
public override bool Exists { get; }
member this.Exists : bool
Public Overrides ReadOnly Property Exists As Boolean
Valore della proprietà
true se il file esiste; false se il file non esiste o se il file è una directory.
Esempio
Nell'esempio di codice seguente viene utilizzata la Exists proprietà assicurarsi che esista un file prima di aprirlo. È possibile usare questa tecnica per generare un'eccezione personalizzata quando il file non viene trovato.
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
Commenti
Quando viene chiamato per la prima volta, FileInfo chiama Refresh e memorizza nella cache le informazioni sul file. Nelle chiamate successive, è necessario chiamare Refresh per ottenere la copia più recente delle informazioni.
La Exists proprietà restituisce false se si verifica un errore durante il tentativo di determinare se il file specificato esiste. Ciò può verificarsi in situazioni che generano eccezioni, ad esempio il passaggio di un nome file con caratteri non validi o troppi caratteri, un errore o un disco mancante o se il chiamante non dispone dell'autorizzazione per leggere il file.