FileInfo.Exists Vlastnost
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Získá hodnotu označující, zda soubor existuje.
public:
virtual property bool Exists { bool get(); };
public override bool Exists { get; }
member this.Exists : bool
Public Overrides ReadOnly Property Exists As Boolean
Hodnota vlastnosti
true pokud soubor existuje; false pokud soubor neexistuje nebo pokud je soubor adresářem.
Příklady
Následující příklad kódu používá Exists vlastnost zajistit, že soubor existuje před jeho otevřením. Tuto techniku můžete použít k vyvolání vlastní výjimky v případě, že soubor nebyl nalezen.
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
Poznámky
Při prvním volání FileInfo volá a Refresh ukládá informace o souboru do mezipaměti. Při dalších voláních musíte zavolat Refresh , abyste získali nejnovější kopii informací.
Vlastnost Exists vrátí false , pokud dojde k nějaké chybě při pokusu o určení, zda zadaný soubor existuje. K tomu může dojít v situacích, kdy vyvoláte výjimky, jako je předání názvu souboru s neplatnými znaky nebo příliš mnoho znaků, selhání nebo chybějící disk nebo pokud volající nemá oprávnění ke čtení souboru.