Quantcast
Channel: Random Findings as a Developer » C#
Viewing all articles
Browse latest Browse all 3

Don't use File when you mean Directory

$
0
0

I was working on a small archiving task for a project and one of the steps is to move a folder from one location to another. Not thinking anything of it, I tried to use File.Exists(archiveFullPath) assuming that a directory would also be considered a file. But for every folder I tried it kept returning false despite them actually existing.

So then I tried switching it over to the similar function but under the Directory object (Directory.Exists(archiveFullPath)) and it worked like a charm, returning true for the specific directories which I knew existed.

To make a long story short, if you are trying to do anything with a directory, use the Directory object instead of the File because directories aren’t treated the same as files.

void Main(string[] args)
{
    string path = @"C:\testing\";
    string working = path + @"Working\";
    string archive = path + @"Archive\";
 
    // Outputs: false
    Console.WriteLine(File.Exists(path));
 
    // Outputs: false
    Console.WriteLine(File.Exists(working));
 
    // Outputs: true
    Console.WriteLine(Directory.Exists(path));
 
    // Outputs: true
    Console.WriteLine(Directory.Exists(working));
 
    // Put the thread to sleep temporarily
    Thread.Sleep(100000); 
}

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images