Supprimer un fichier en C#

Supprimer un fichier en C#

Ce didacticiel présentera des méthodes pour supprimer un fichier à un chemin spécifique en C#.

Supprimer un fichier avec la fonction File.Delete(path) en C#

La fonction File.Delete(path) permet de supprimer le fichier à l’intérieur du chemin path en C#. L’exemple de code suivant nous montre comment supprimer un fichier d’un chemin spécifié avec la fonction File.Delete() en C#.

using System;
using System.IO;

namespace check_whether_a_file_exists {
  class Program {
    static void Main(string[] args) {
      string path = "C:\\filefolder\\file.txt";
      bool result = File.Exists(path);
      if (result == true) {
        Console.WriteLine("File Found");
        File.Delete(path);
        Console.WriteLine("File Deleted Successfully");
      } else {
        Console.WriteLine("File Not Found");
      }
    }
  }
}

Production:

File Found File Deleted Successfully

Nous avons supprimé un fichier dans le chemin C:\\filefolder\\file.txt avec la fonction File.Delete() en C#. Notre programme vérifie d’abord si un fichier existe à l’intérieur du path ou non avec la fonction File.Exists(). Si le fichier existe, le programme supprime le fichier avec la fonction File.Delete(). Si le fichier n’existe pas, le programme affiche File Not Found.

Vous aimez nos tutoriels ? Abonnez-vous à DelftStack sur YouTube pour nous aider à créer davantage de tutoriels vidéo de haute qualité. Abonnez-vous
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Article connexe - Csharp File