3

I'm getting the user to pass a path as a string.

A path could be something like

C:\someFolder

C:\someFolder\someFile

C:\someFolder\someFile.jpg

I want to check if the given path is a file or folder, and if it is a file, I want to check if it actually exits.

I've been using FileAttributes fileRoot = File.GetAttributes(@path); to check if its a file or a folder but it doesn't work properly.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
  • 1
    I think fileAttributes works properly to identify if it a file or directory. can you please tell me why it is not working properly? – jadavparesh06 Oct 09 '14 at 05:24
  • 1
    Duplicate of [Better way to check if Path is a File or a Directory?](http://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory) – Prix Oct 09 '14 at 05:25
  • The question is duplicate, next time try to search at least in SO ! http://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory?lq=1 – mybirthname Oct 09 '14 at 05:40
  • @mybirthname I checked that question out. It didn't have anything about the file possibly not existing. –  Oct 09 '14 at 05:59

5 Answers5

11
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\";
            FileAttributes attributes = File.GetAttributes(path);

            switch (attributes)
            {
                case FileAttributes.Directory:
                    if (Directory.Exists(path))
                        Console.WriteLine("This directory exists.");
                    else
                        Console.WriteLine("This directory does not exist.");
                    break;
                default:
                    if (File.Exists(path))
                        Console.WriteLine("This file exists.");
                    else
                        Console.WriteLine("This file does not exist.");
                    break;
            }
        }
    }
}

Here's a working sample I wrote for you. It gets the path variable, determines whether it's a dir or a file and then checks to see if it exists. Just make sure you handle the FileAttributes attributes = File.GetAttributes(path); line appropriately such as placing it in a try/catch block because if the file or folder does not exist it will throw an exception.

jay_t55
  • 11,362
  • 28
  • 103
  • 174
  • Thank you for your quick and complete answer. –  Oct 09 '14 at 05:54
  • You're very welcome. Just make sure you handle the `FileAttributes attributes = File.GetAttributes(path);` line appropriately such as placing it in a try/catch block because if the file or folder does not exist it will throw an exception. – jay_t55 Oct 09 '14 at 06:02
  • Ha, yes I just realized that. –  Oct 09 '14 at 06:11
  • Sorry haha, I should have included that in my answer. – jay_t55 Oct 09 '14 at 06:42
4
    static void Main(string[] args)
    {
        string Path = @"C:\Abhishek\Documents";
        string filePath = @"C:\Abhishek\Documents.txt";
        bool isDirExists = Directory.Exists(Path);
        bool isFileExists = File.Exists(filePath);

        if (isDirExists)
        {
            Console.WriteLine("Directory Exists");
        }
        else {
            Console.WriteLine("Directory does not exists");
        }
        if (isFileExists)
        {
            Console.WriteLine("File Exists");
        }
        else
        {
            Console.WriteLine("File does not exists");
        }
        Console.ReadKey();
    }
jay_t55
  • 11,362
  • 28
  • 103
  • 174
Abhishek
  • 196
  • 11
  • 2
    This does not solve the OP's problem. This requires you to know in advance whether the string is a Directory or a File. – jay_t55 Oct 09 '14 at 05:33
  • @jay_t55 this is the right way to do it, the up voted answer doesn't work in every case ! He just need to check only with one string ... – mybirthname Oct 09 '14 at 05:39
  • Yes but there is possibility that there exists directory as well as file with same name. – Abhishek Oct 09 '14 at 05:59
2

You can use File.Exists to check if the file exists.

You can use Directory.Exists to check if folders exist

And then you can use this to check if it is a file or folder

private bool CheckIfExists(string path)
{
    // get the file attributes for file or directory
    FileAttributes attr = File.GetAttributes(path);

    //detect whether its a directory or file
    if((attr & FileAttributes.Directory) == FileAttributes.Directory)
        return Directory.Exists(path);
    else
        return File.Exists(path);
}
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
0

Would you please clarify this statement:

but it doesn't work properly

What are the cases for "not properly"?

Regarding question:

Does your task require to know if its file or directory?

In case no (i.e. you just want to have "true" if file exists), you can use File.Exists and get needed result. No exceptions thrown in case you're worried.

var filePath = @"d:\Storage\Repo\Detrack\Detrack.bak";
var dirPath = @"d:\Storage\Repo\Detrack\";
var dirPathWithoutTrailingSlash = @"d:\Storage\Repo\Detrack";

Console.WriteLine("Path ({0}) exists = {1}", filePath, new FileInfo(filePath).Exists);
Console.WriteLine("Path ({0}) exists = {1}", dirPath, new FileInfo(dirPath).Exists);
Console.WriteLine("Path ({0}) exists = {1}", dirPathWithoutTrailingSlash, new FileInfo(dirPathWithoutTrailingSlash).Exists);
Console.ReadLine();

Results are:

Path (d:\Storage\Repo\Detrack\Detrack.bak) exists = True
Path (d:\Storage\Repo\Detrack\) exists = False
Path (d:\Storage\Repo\Detrack) exists = False
Artem O.
  • 85
  • 5
  • I wasn't aware that there were two checks for `exists` -`Directory.Exists` and `File.Exists` and therefore I was getting wrong results, which was why I thought it wasn't working correctly. Sorry about that. –  Oct 09 '14 at 05:53
0

You can use this code below to check it:

// get the file attributes for file or directory
        FileAttributes attr = File.GetAttributes(@"c:\Temp");

        //detect whether its a directory or file
        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
        {
            // Its a directory
            // Do something here
        }
        else
        {
            // Its a file
            // Do something here
        }