File.Exists-Methode

Bestimmt, ob die angegebene Datei vorhanden ist.

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function Exists ( _
    path As String _
) As Boolean
'Usage
Dim path As String
Dim returnValue As Boolean

returnValue = File.Exists(path)
public static bool Exists (
    string path
)
public:
static bool Exists (
    String^ path
)
public static boolean Exists (
    String path
)
public static function Exists (
    path : String
) : boolean

Parameter

  • path
    Die zu überprüfende Datei.

Rückgabewert

true, wenn der Aufrufer über die erforderlichen Berechtigungen verfügt und path den Namen einer vorhandenen Datei enthält, andernfalls false. Diese Methode gibt auch false zurück, wenn für pathNULL (Nothing in Visual Basic), ein ungültiger Pfad oder eine Zeichenfolge der Länge 0 (null) festgelegt ist. Wenn ein Aufrufer nicht über ausreichende Berechtigungen zum Lesen der angegebenen Datei verfügt, wird keine Ausnahme ausgelöst, und die Methode gibt false zurück, unabhängig vom Vorhandensein von path.

Hinweise

Die Exists-Methode sollte nicht für die Pfadvalidierung verwendet werden. Diese Methode überprüft in erster Linie, ob die im path angegebene Datei vorhanden ist. Wenn ein ungültiger Pfad an Exists übergeben wird, wird false zurückgegeben.

Zwischen dem Aufrufen der Exists-Methode und dem Ausführen eines anderen Vorgangs für die Datei, z. B. Delete, ist es jedoch möglich, dass ein anderer Prozess auf die Datei zugreift und diese ändert. Daher empfiehlt es sich, die Exists-Methode mit einem Wrapper zu versehen, und die für die Datei auszuführenden Vorgänge in einen try...catch-Block einzuschließen, wie im Beispiel dargestellt. Mit dieser Maßnahme können Sie potenzielle Konflikte eingrenzen. Durch den Einsatz der Exists-Methode erhöht sich die Wahrscheinlichkeit, dass die Datei verfügbar ist, er bietet jedoch keine Garantie.

Mit dem path-Parameter dürfen relative oder absolute Pfadinformationen angegeben werden. Relative Pfadinformationen werden relativ zum aktuellen Arbeitsverzeichnis interpretiert. Informationen über das Abrufen des aktuellen Arbeitsverzeichnisses finden Sie unter GetCurrentDirectory.

Wenn path ein Verzeichnis beschreibt, gibt diese Methode false zurück. Nachstehende Leerzeichen werden aus dem path-Parameter entfernt, bevor bestimmt wird, ob die Datei vorhanden ist.

Beispiel

Im folgenden Beispiel wird veranschaulicht, wie Sie eine Datei mithilfe der Exists-Methode besser vor dem Überschreiben schützen können.

Imports System
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim path2 As String = path + "temp"
        Try
            Dim sw As StreamWriter = File.CreateText(path)
            sw.Close()
            ' Do the Copy operation only if the first file exists
            ' and the second file does not.
            If File.Exists(path) Then
                If File.Exists(path2) Then
                    Console.WriteLine("The target file already exists.")
                Else
                    'try to copy it
                    File.Copy(path, path2)
                    Console.WriteLine("{0} was copied to {1}.", path, path2)
                End If
            Else
                Console.WriteLine("The source file does not exist.")
            End If
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = path + "temp";
        try 
        {
            using (StreamWriter sw = File.CreateText(path)) {}

            // Only do the Copy operation if the first file exists
            // and the second file does not.
            if (File.Exists(path)) 
            {
                if (File.Exists(path2)) 
                {
                    Console.WriteLine("The target already exists");
                } 
                else 
                {
                    // Try to copy the file.
                    File.Copy(path, path2);
                    Console.WriteLine("{0} was copied to {1}.", path, path2);
                }
            } 
            else 
            {
                Console.WriteLine("The source file does not exist.");
            }
        } 
        catch 
        {
            Console.WriteLine("Double copying is not allowed, as expected.");
        }
    }
}
using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   String^ path2 = String::Concat( path, "temp" );
   try
   {
      StreamWriter^ sw = File::CreateText( path );
      if ( sw )
            delete (IDisposable^)sw;
      
      // Only do the Copy operation if the first file exists
      // and the second file does not.
      if ( File::Exists( path ) )
      {
         if ( File::Exists( path2 ) )
         {
            Console::WriteLine( "The target already exists" );
         }
         else
         {
            // Try to copy the file.
            File::Copy( path, path2 );
            Console::WriteLine( "{0} was copied to {1}.", path, path2 );
         }
      }
      else
      {
         Console::WriteLine( "The source file does not exist." );
      }
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "Double copying is not allowed, as expected." );
   }
}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";
        String path2 = path + "temp";

        try {            
            StreamWriter sw = File.CreateText(path);
            try {
            }
            finally {
                sw.Dispose();
            }

            // Only do the Copy operation if the first file exists
            // and the second file does not.
            if (File.Exists(path)) {
                if (File.Exists(path2)) {
                    Console.WriteLine("The target already exists");
                }
                else {
                    // Try to copy the file.
                    File.Copy(path, path2);
                    Console.WriteLine("{0} was copied to {1}.", path, path2);
                }
            }
            else {
                Console.WriteLine("The source file does not exist.");
            }
        }
        catch (System.Exception exp) {
            Console.WriteLine("Double copying is not allowed, as expected.");
        }
    } //main
} //Test

.NET Framework-Sicherheit

Plattformen

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

File-Klasse
File-Member
System.IO-Namespace

Weitere Ressourcen

Datei- und Stream-E/A
Gewusst wie: Lesen aus einer Textdatei
Gewusst wie: Schreiben von Text in eine Datei