FileInfo.Exists Egenskap

Definition

Hämtar ett värde som anger om en fil finns.

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

Egenskapsvärde

true om filen finns; false om filen inte finns eller om filen är en katalog.

Exempel

I följande kodexempel används Exists egenskapen se till att en fil finns innan den öppnas. Du kan använda den här tekniken för att skapa ett anpassat undantag när filen inte hittas.

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

Kommentarer

När den först anropas FileInfo anropas Refresh och cachelagrar information om filen. Vid efterföljande anrop måste du anropa Refresh för att få den senaste kopian av informationen.

Egenskapen Exists returnerar false om något fel inträffar när du försöker avgöra om den angivna filen finns. Detta kan inträffa i situationer som skapar undantag som att skicka ett filnamn med ogiltiga tecken eller för många tecken, en disk som misslyckas eller saknas eller om anroparen inte har behörighet att läsa filen.

Gäller för

Se även