C# File.Exists is not finding files

moondaddy 911 Reputation points
2021-11-09T23:36:04.757+00:00

I have a small console app that gets a list of files and their paths from a database, then loops through the list checking to see if the file actually exists. For some reason "File.Exists" always returns false, even when the file does exist. Here's my code:

bool found = File.Exists(item.FilePath + item.FileName);
if (found == false)
{
    LogMissingFilesV2(item.FileId.ToString(), item.FilePath, item.FileName);
}
else
{
    Console.WriteLine(item.FileName);
}

found is always false.

and here's and example of a full path where the file does exists and found = false:

D:\Sites\TransAct\TA_054\FS\Agreement\dea4d6fa-d410-4324-9d7b-39840020d76c_7-ROHDE 2-1H ARO DOCUMENTS.pdf

To make sure the path is correct I find the file in File Explorer, copy its path and then name into notepad and compare. they are both exactly the same

Also, if I search this string in File Explorer:

dea4d6fa-d410-4324-9d7b-39840020d76c_7-ROHDE 2-1H ARO DOCUMENTS.pdf

File Explorer cannot find the file but if I search on:

dea4d6fa-d410-4324-9d7b-39840020d76c

I can find it. Its like the name is too complex.

How can it make this work as intended?

Thank you

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,277 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2021-11-10T01:42:12.917+00:00

    Try and get the directory name e.g. Path.GetDirectoryName, then use Directory.GetCurrentDirectory, remember it in a variable then use Directory.SetCurrentDirectory to the directory then try using File.Exists via Path.GetFileName. So what you are doing is eliminating the directory name and searching just on the file name. When done use Directory.SetCurrentDirectory

    0 comments No comments