How to Check if a File Exists in .NET Core Using C#.Net

How to check a file exists in a folder or not in .net core using c#.net. Example tutorial to validate the path by File.Exists(Path) method in c#.
In today's article will use a simple tutorial with an example to check or validate a file exists in a given path in .NET core using c#.net. Here we will use a console application to validate the file exists. By using File.Exists(Path) to validate the given path of the file is valid or file exists or not. 

Now for lets first create a new folder and add a file in it. Please check the below file location. 

Folder With txt File In .Net Core

Here in above code, we are having a text file in folder. Now let's check the below code. 
string folderPath = "D:\\DemoProject\\DemoFolder\\";
string fileName = "codemantra99.txt";
string finalPath = string.Format("{0}{1}", folderPath, fileName);
Console.WriteLine("Folder Path: "+folderPath);
Console.WriteLine("File Name: " + fileName);
if (File.Exists(finalPath))
{
    Console.WriteLine(string.Format("File '{0}' exists.", fileName));
}
else
{
      Console.WriteLine(string.Format("File '{0}' does not exists. ", fileName));
}
In above code I have defined two different variables first for the folder path and second one is for the file name. Now I have used string.Format(format, object) to concatenate or combine the string variables to get the complete path of the file. 

After that I have used File.Exists(Path) to validate file exists. now let's run the code to check the output. 

Validate File Exists in a Folder in Net Core

Here we can see that the file exists in the given location. Now lets delete the file or rename it and then validate.

File Path With .txt File in Net Core

Now let's execute the code to check the output.

File Does Not Exists in Folder in .Net core

Post a Comment