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
- string curFile = @"c:\temp\sample.txt";
- 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
- [System.Runtime.InteropServices.ComVisible (true)]
- 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.
- Using System;
- Using System.IO;
- Class Test {
- public static void Main() {
- string path = @ "c:\temp\MySample.txt";
- if (!File.Exists(path)) {
- using(Stream Writer sw = File.Create Text(path)) {
- sw.WriteLine("Hello");
- sw.WriteLine("And");
- sw.WriteLine("Welcome");
- }
- }
- using(Stream Reader sr = File.Open Text(path)) {
- strings;
- while ((s = sr.ReadLine()) != null) {
- Console.WriteLine(s);
- }
- }
- }
- }
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
- 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.
-
- Using System;
- Using System.IO;
- Using System.Collections;
- Public class Recursive File Processor {
- public static void Main(string[] args) {
- foreach(string path in args) {
- if (File.Exists(path)) {
- (Directory.Exists(path)) {
- Process Directory(path);
- } else {
- Console.Write Line("{1} is not a valid file or directory.", path);
- }
- }
- }
- public static void Process Directory(string target Directory) {
- string[] file Entries = Directory.GetFiles(target Directory);
- foreach(string fileName infileEntries) ProcessFile(fileName);
- string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
- foreach(stringsubdirectory in subdirectoryEntries) ProcessDirectory(subdirectory);
- }
- public static void ProcessFile(string path) {
- Console.WriteLine("Processed file '{0}'.", path);
- }
- }
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.
- public static string GetCurrentDirectory ();
Example
The following example demonstrates how to use the GetCurrentDirectory method.
- Using System;
- Using System.IO;
- Class Test {
- public static void Main() {
- try {
- String path = Directory.GetCurrentDirectory();
- String target = @ "D:\temp";
- Console.Write Line("The current directory is {0}", path);
- if (!Directory.Exists(target)) {
- Directory.CreateDirectory(target);
- }
- (target);
- if (path.Equals(Directory.GetCurrentDirectory())) {
- Console.Write Line("You are in the temp directory.");
- }
- Else {
- Console.WriteLine("You are not in the temp directory.");
- }
- } catch (Exception e) {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
- }
- }
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.
- string fileName = @ "c:\temp\Mahesh.txt";
- if (File.Exists(fileName))
- Console.WriteLine("File exists.");
- else
- Console.WriteLine("File does not exist.");
- After that check whether the file exists in a directory or not.
- if(File.Exists(@ "D:\myfile.txt")) {
- Console.WriteLine("The file exists.");
- }
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#.
- namespace ConsoleApp {
- class Program {
- static void Main() {
- if (File.Exists("MyFile.txt")) {
- Console.WriteLine("File exists...");
- } else {
- Console.WriteLine("File does not exist in the current directory!");
- }
- if (File.Exists(@ "D:\myfile.txt")) {
- Console.WriteLine("File exists...");
- } else {
- Console.WriteLine("File does not exist in the D directory!");
- }
- }
- }
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#.