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#?
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#"
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly