john john - 2 months ago 15
C# Question

Check if file or folder by given path exists

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.

Answer
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.