FileInfo.Exists 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得值,這個值指出檔案是否存在。
public:
virtual property bool Exists { bool get(); };
public override bool Exists { get; }
member this.Exists : bool
Public Overrides ReadOnly Property Exists As Boolean
屬性值
如果檔案存在,則為 true
;如果檔案不存在或者檔案是目錄,則為 false
。
範例
下列程式代碼範例會使用 屬性, Exists 確保檔案存在,再開啟它。 當找不到檔案時,您可以使用這項技術擲回自定義例外狀況。
array<Byte>^ Openfile(String^ fileName)
{
// Check the fileName argument.
if (fileName == nullptr || fileName->Length == 0)
{
throw gcnew ArgumentNullException("fileName");
}
// Check to see if the file exists.
FileInfo^ fInfo = gcnew FileInfo(fileName);
// You can throw a personalized exception if
// the file does not exist.
if (!fInfo->Exists)
{
throw gcnew FileNotFoundException("The file was not found.",
fileName);
}
try
{
// Open the file.
FileStream^ fStream = gcnew FileStream(fileName, FileMode::Open);
// Create a buffer.
array<Byte>^ buffer = gcnew array<Byte>(fStream->Length);
// Read the file contents to the buffer.
fStream->Read(buffer, 0, (int)fStream->Length);
// return the buffer.
return buffer;
}
catch (IOException^ ex)
{
Console::WriteLine(ex->Message);
return nullptr;
}
}
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
備註
第一次呼叫時, FileInfo 呼叫 Refresh 並快取檔案的相關信息。 在後續呼叫時,您必須呼叫 Refresh 以取得最新的資訊複本。
如果嘗試判斷指定的檔案是否存在,屬性 Exists 會傳回 false
如果發生任何錯誤。 這可能會在引發例外狀況的情況下發生,例如傳遞無效字元或太多字元的檔名、失敗或遺失的磁碟,或呼叫端沒有讀取檔案的許可權。