john john - 1 year ago 153
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




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 Source
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.");
                        Console.WriteLine("This directory does not exist.");
                    if (File.Exists(path))
                        Console.WriteLine("This file exists.");
                        Console.WriteLine("This file does not exist.");

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download