1

I am trying to list all the files in the Documents folder using an absolute path in C# using this C:\\Users\\USER\\Documents, I check first if the path exists and then try to list all the files in that location but my conditional structure is returning false while the path exists on my machine, I guess the double slash is for escaping the single slash characters. Why is my code returning false for the File.Exists(path) and the path does exist on my machine as C:\Users\USER\Documents

public class Solution
    {
        private static string[] files;
        static void Main(string[] args)
        {
            string path = "C:\\Users\\USER\\Documents";
            //check if the path exists
            if (File.Exists(path))
            {
                //list all the files in the path
                files = Directory.GetFiles(path);
                //check if the count is greater than 0
                if (files.Length > 0)
                {
                    foreach (string r in files)
                    {
                        Console.WriteLine(r);
                    };
                }
                else
                {
                    Console.WriteLine("This file location is empty");
                }
            }
            else
            {
                //this section executes so the path is returning false
                Console.WriteLine("Path does not exist");
            }
        }
    }
TechGeek
  • 316
  • 1
  • 11
  • 3
    `File.Exists` is only for files. Use `Directory.Exists` for folders. – wohlstad Jun 19 '22 at 09:53
  • @wohlstad, aha I learnt something new , Thanks – TechGeek Jun 19 '22 at 09:53
  • 2
    You presumably want the Documents folder of the current user? `string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);` – Ralf Jun 19 '22 at 09:55
  • 1
    Have you checked for "does this question already exist?" – Orace Jun 19 '22 at 09:57
  • @Orace, no it does not answer because the solution provided in the referenced document uses FileAttributes class and involves the use of further conditional structures to check if path is a file or directory, since I have the knowledge of the type of file, the answer in this post serves me well – TechGeek Jun 19 '22 at 10:17

1 Answers1

3

File.Exists checks if a file exists, NOT a directory - it is the reason you get false.

To check if a directory exists use Directory.Exists:

if (Directory.Exists(path))
{
    // your code
}
Roman
  • 11,966
  • 10
  • 38
  • 47