Check if a file path is valid in c# code example

Example 1: how to check file path is valid in c#

string path="D://files"
if (!Directory.Exists(path))
                {
                    MessageBox.Show("Path is not valid please check if this path exists or not","Path Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

Example 2: c# check if string is path or file

// 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)
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");