How to Check File Exist in C#

Hi programmers, welcome to new post of c#.net. This post i’ll write program to check file exists or not using c# console application. In the code i’m using FileInfo class, It is used with instance methods for the creation, copying, deletion, moving, and opening of files. Its comes under System.IO.FileStream namespace. Next important property i used Exists : it checks whether a file exists or not. Let’s see the codes.

Directly use below codes in Editor

using System;
using System.IO;
namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = @"C:\Users\Adam\Desktop\adam.txt";
            FileInfo fi = new FileInfo(str);            
            if (fi.Exists)
            {
                Console.WriteLine("File Found {0}" ,fi.Exists);
                long len = fi.Length;
                Console.WriteLine("File Size in Bytes : "+ len);
 
                bool b1 = fi.IsReadOnly;
                Console.WriteLine("Is ReadOnly : " + b1);
                //fi.Delete(); To permanently delete a file 
                //Console.WriteLine("File Deleted ");
            }
            else
            {
                Console.WriteLine("Ahh... Invalid File");
            }
        }
    }
}

Happy Coding…Thanks.

Post Author: adama