How To Check If A File Exists In C#

Introduction

The File.Exists method checks if a file exists in C# at a specified location. The File class is defined in the System.IO namespace. If the File.Exists method returns true; the file exists, and the else file does not exist.

The following example demonstrates how to use the File class to check whether a file exists in the 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. Note: Before you run this code, make sure you create a c:\temp folder on your machine. OR change this folder to where you want to create a new file.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MySample.txt";

        if (!File.Exists(path))
        {
            // Create a file to write to
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}

Directory.Exists(String) Method

The Directory.Exists checks 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 RecursiveFileProcessor
{
    public static void Main(string[] args)
    {
        foreach (string path in args)
        {
            if (File.Exists(path))
            {
                // This path is a file
                ProcessFile(path);
            }
            else if (Directory.Exists(path))
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }
        }
    }

    // Process all files in the directory passed in, recurse on any directories
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string[] fileEntries = Directory.GetFiles(targetDirectory);
        foreach (string fileName in fileEntries)
        {
            ProcessFile(fileName);
        }

        // Recurse into subdirectories of this directory.
        string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach (string subdirectory in subdirectoryEntries)
        {
            ProcessDirectory(subdirectory);
        }
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path)
    {
        Console.WriteLine("Processed file '{0}'.", path);
    }
}

We can use another process to potentially do something with the file 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.

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
        {
            // Get the current directory.
            string path = Directory.GetCurrentDirectory();
            string target = @"D:\temp";
            
            Console.WriteLine("The current directory is {0}", path);
            
            if (!Directory.Exists(target))
            {
                Directory.CreateDirectory(target);
            }
            
            // Change the current directory.
            Environment.CurrentDirectory = target;
            
            if (path.Equals(Directory.GetCurrentDirectory()))
            {
                Console.WriteLine("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, the one from which the process 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 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 the 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.");
}

// 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, and this method merely checks if the file specified in the 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 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#. 

using System;
using System.IO;

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

The file does not exist in the current directory!

The file does not exist in the D directory!

Summary

This article taught us how to check if a file exists in C#.  


Similar Articles