Check if a File Exists in C#

Introduction

 
This article shows the File.Exists method from C#.
 

The File Existing Method  

 
The File exists method is used to check if a particular file exists.
 
System.IO namespace.
 
File.Existing method is a specific file that exists in c# there are several ways of testing file existence. File.Exists is the easiest. It is the simplest way of checking that the file exists. It returns true or false in the file.
 

Boolean

 
This method used to Day and night are parts of a Boolean condition. The day is true (it has a light) and night is false. This can be stored in a bool variable in file Existing Method The True Condition, if the caller has the required permissions and path, contains the name of an existing file; otherwise, false. This method also returns false if the path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path in a Boolean statement.
 
Syntax
  1. string curFile = @"c:\temp\sample.txt";    
  2. Console.WriteLine(File.sample(curFile) ? "File exists." : "File does not exist.");     
The Exists method should not be used for path validation, this method merely checks if the file specified in path exists file. And Passing an invalid path to Exists returns false. To check whether the path contains any invalid characters, we can call the GetInvalidPathChars method to retrieve the characters that are invalid for the file system. we can also create a regular expression to test whether the path is valid for your environment.
 
For examples of acceptable paths, see File.
 

File Class

 
The File Class is Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
 
Syntax 
  1. [System.Runtime.InteropServices.ComVisible (true)]     
  2. Public static class File    
Example
 
The following example demonstrates how to use the File class to check whether a file exists in File class, and depending on the result, either create a new file and write to it or open the existing file and read from it. Before running the code, create a c:\temp folder. 
  1. Using System;  
  2. Using System.IO;  
  3. Class Test {  
  4.  public static void Main() {  
  5.   string path = @ "c:\temp\MySample.txt";  
  6.   if (!File.Exists(path)) { // Create a file to write to   
  7.    using(Stream Writer sw = File.Create Text(path)) {  
  8.     sw.WriteLine("Hello");  
  9.     sw.WriteLine("And");  
  10.     sw.WriteLine("Welcome");  
  11.    }  
  12.   } // Open the file to read from.  
  13.   using(Stream Reader sr = File.Open Text(path)) {  
  14.    strings;  
  15.    while ((s = sr.ReadLine()) != null) {  
  16.     Console.WriteLine(s);  
  17.    }  
  18.   }  
  19.  }  
  20. }  
To check if a directory exists, see Directory.Exists.  
 

Directory.Exists(String) Method

 
The Directory.Exists is Determines whether the given path refers to an existing directory on disk.
 
Syntax
  1. public static bool Exists (string path);  

Example

This example takes an array of file or directory names on the command line, determines what kind of name it is, and processes it appropriately.
  1. // For File.Exists, Directory.Exists  
  2. Using System;  
  3. Using System.IO;  
  4. Using System.Collections;  
  5. Public class Recursive File Processor {  
  6.  public static void Main(string[] args) {  
  7.   foreach(string path in args) {  
  8.    if (File.Exists(path)) { // This path is a file Process File(path); } else if  
  9.     (Directory.Exists(path)) { // This path is a directory   
  10.      Process Directory(path);  
  11.     } else {  
  12.      Console.Write Line("{1} is not a valid file or directory.", path);  
  13.     }  
  14.    }  
  15.   } // Process all files in the directory passed in, recurse on any directories // that are found, and process the files they contain.  
  16.   public static void Process Directory(string target Directory) { // Process the list of files found in the directory.  
  17.    string[] file Entries = Directory.GetFiles(target Directory);  
  18.    foreach(string fileName infileEntries) ProcessFile(fileName); // Recurse into subdirectories of this directory.  
  19.    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);  
  20.    foreach(stringsubdirectory in subdirectoryEntries) ProcessDirectory(subdirectory);  
  21.   } // Insert logic for processing found files here.  
  22.   public static void ProcessFile(string path) {  
  23.    Console.WriteLine("Processed file '{0}'.", path);  
  24.   }  
  25.  }  
We can use another process to potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.
 
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.  
 

Directory.Get Current Directory Method

 
This method gets the current working directory of the application in the file existing method.
  1. public static string GetCurrentDirectory ();   
Example
 
The following example demonstrates how to use the GetCurrentDirectory method.
  1. Using System;  
  2. Using System.IO;  
  3. Class Test {  
  4.  public static void Main() {  
  5.   try { // Get the current directory.  
  6.    String path = Directory.GetCurrentDirectory();  
  7.    String target = @ "D:\temp";  
  8.    Console.Write Line("The current directory is {0}", path);  
  9.    if (!Directory.Exists(target)) {  
  10.     Directory.CreateDirectory(target);  
  11.    } // Change the current directory.Environment.Current Directory =   
  12.    (target);  
  13.    if (path.Equals(Directory.GetCurrentDirectory())) {  
  14.     Console.Write Line("You are in the temp directory.");  
  15.    }  
  16.    Else {  
  17.     Console.WriteLine("You are not in the temp directory.");  
  18.    }  
  19.   } catch (Exception e) {  
  20.    Console.WriteLine("The process failed: {0}", e.ToString());  
  21.   }  
  22.  }  
  23. }  
The current directory is distinct from the original directory, which is the one from which the process was started.
 
If the path describes a directory, this method returns false. Trailing spaces are removed from the path parameter before determining if the file exists.
 
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
 
Note
 
Bool is often used in expressions. Many expressions evaluate to a boolean value. Represented in one byte, the bool type represents truth.
 
True, false 
 
True and false are boolean literals. They are values that mean yes and no. They can be stored in variables of type bool in file existing.
 
The file Exists method checks if the specified file exists. The following code snippet checks if a file exists or not.
  1. string fileName = @ "c:\temp\Mahesh.txt";  
  2. if (File.Exists(fileName))  
  3.  Console.WriteLine("File exists.");  
  4. else  
  5.  Console.WriteLine("File does not exist.");  
  6. After that check whether the file exists in a directory or not.  
  7. if(File.Exists(@ "D:\myfile.txt")) {  
  8.  Console.WriteLine("The file exists.");  
  9. }  
The file Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Exists returns false. To check whether the path contains any invalid characters, you can call the GetInvalidPathChars method to retrieve the characters that are invalid for the file system. You can also create a regular expression to test whether the path is valid for your environment. For examples of acceptable paths, see File. 
 
To check if a directory exists, see Directory.Exists.
 
Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete. 
 
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
 
If the path describes a directory, this method returns false. Trailing spaces are removed from the path parameter before determining if the file exists.
 
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
 
Let us see the complete example to check if a file exists in C#. 
  1. namespace ConsoleApp {  
  2.  class Program {  
  3.   static void Main() {  
  4.    if (File.Exists("MyFile.txt")) {  
  5.     Console.WriteLine("File exists...");  
  6.    } else {  
  7.     Console.WriteLine("File does not exist in the current directory!");  
  8.    }  
  9.    if (File.Exists(@ "D:\myfile.txt")) {  
  10.     Console.WriteLine("File exists...");  
  11.    } else {  
  12.     Console.WriteLine("File does not exist in the D directory!");  
  13.    }  
  14.   }  
  15.  }  
Output
 
File does not exist in the current directory!
 
File does not exist in the D directory!
 

Summary 

 
In this article, we learned how to check if a file exists in C#.