How to check if File exists in C#? (Inside folder)


I am trying to download a file from a url, and there are many files, but I don't want to download files that already exists in my drive. So I want to implement to check if file already exists in a folder using C#?


Asked by:- bhanu
0
: 4384 At:- 5/20/2020 7:33:12 AM
C# file-io file exists in folder







1 Answers
profileImage Answered by:- vikas_jk

You can simple call File.Exists(path), where path can contain folder or complete directory url, which will return true if file exists or false it doesn't exists.

var FileURL=@"C:\DriveFolder\file.txt";
if(!File.Exists(FileURL))
{
  //create file, as files doesn't exists.
}

Note: Passing an invalid path to .Exists method, it returns false

Also it will return false, if user doesn't have permission to read file in the specified file path url.

You can also check if file exists using FileInfo

DirectoryInfo di = new DirectoryInfo(ProcessingDirectory);
FileInfo[] myFiles = di.GetFiles("*.txt");
if (myFiles.Length == 0)
{
    Console.WriteLine("No File");
}
foreach (var fInfo in myFiles)   
{
    if (!fInfo.Exists)
    {
        throw new FileNotFoundException("The file was not found.", FileName);
    }
}

You can also read, more about file operations in C# here "File I/O in C#"

1
At:- 5/20/2020 11:42:03 AM
Thanks for quick reply. 0
By : bhanu - at :- 5/28/2020 1:07:26 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use