File.Exists, méthode (System.IO)

Bibliothèque de classes .NET Framework 
File.Exists, méthode 

Détermine si le fichier spécifié existe.

Espace de noms : System.IO
Assembly : mscorlib (dans mscorlib.dll)

SyntaxeSyntaxe


Visual Basic (Déclaration)
Public Shared Function Exists ( _
    path As String _
) As Boolean


Visual Basic (Utilisation)
Dim path As String
Dim returnValue As Boolean

returnValue = File.Exists(path)


C#
public static bool Exists (
    string path
)


C++
public:
static bool Exists (
    String^ path
)


J#
public static boolean Exists (
    String path
)


JScript
public static function Exists (
    path : String
) : boolean

Paramètres

path

Fichier à contrôler.

Valeur de retour

true si l'appelant a les autorisations requises et si path contient le nom d'un fichier existant ; sinon false. Cette méthode retourne également false si path est référence Null (Nothing en Visual Basic), un chemin d'accès non valide ou une chaîne de longueur nulle. Si l'appelant n'a pas les autorisations suffisantes pour lire le fichier spécifié, aucune exception n'est levée et la méthode retourne false quelle que soit l'existence de path.
NotesNotes

La méthode Exists ne doit pas être utilisée pour la validation de chemin d'accès car elle vérifie simplement si le fichier spécifié dans path existe. Le passage d'un chemin d'accès non valide à Exists retourne false.

Sachez qu'un autre processus peut effectuer une opération sur le fichier entre le moment où vous appelez la méthode Exists et celui où vous effectuez une autre opération sur le fichier, telle que Delete. Une méthode de programmation recommandée consiste à encapsuler la méthode Exists, et les opérations que vous effectuez sur le fichier, dans un bloc try...catch comme indiqué dans l'exemple. Cela permet de limiter la portée pour les conflits potentiels. La méthode Exists permet uniquement de vous assurer que le fichier sera disponible, mais elle n'offre aucune garantie.

Le paramètre path est autorisé à spécifier des informations sur le chemin d'accès relatif ou absolu. Les informations sur le chemin d'accès relatif sont interprétées comme étant relatives au répertoire de travail en cours. Pour obtenir le répertoire de travail en cours, consultez GetCurrentDirectory.

Si path décrit un répertoire, cette méthode retourne false. Les espaces de fin sont supprimés du paramètre path avant de déterminer si le fichier existe.

ExempleExemple

L'exemple suivant utilise la méthode Exists pour vérifier qu'un fichier n'est pas substitué.



Visual Basic
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


C#
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.");
        }
    }
}


C++
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." );
   }
}


J#
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
Sécurité .NET FrameworkSécurité .NET Framework
Plates-formesPlates-formes

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

Informations de versionInformations de version

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0
Voir aussiVoir aussi

Ces informations proviennent du site de http://msdn2.microsoft.com
Source de cette page : http://msdn2.microsoft.com/fr-fr/library/system.io.file.exists.aspx

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

8 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-4807
Document créé le 30/10/06 01:25, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-system.io.file.exists.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,42 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
La difficulté, ce n'est pas de rêver, mais d'accepter et de comprendre les rêves des autres.

Zhang Xianliang
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 04:40, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)