-5

i used DirectoryInfo to get files from a folder.

but let say the directory to the folder does not exist

i want a message that says ("directory not found")

        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\nour\Desktop\Gedaan");
        FileInfo[] Files = dinfo.GetFiles("*.DOCX");
        foreach (FileInfo file in Files)
        {

            LB2.Items.Add(file.Name);
        }
Smmit
  • 31
  • 6
  • 6
    You certainly have searched for existing answers before asking. What makes this question different to others where it was explained how to check whether a directory exists or not? Why `Directory.Exists` or `DirectoryInfo.Exists` don't work for you? – Tim Schmelter Oct 02 '18 at 13:35
  • 2
    [I downvoted because research must be done to ask a good question](http://idownvotedbecau.se/noresearch/). – EJoshuaS - Stand with Ukraine Oct 02 '18 at 13:45
  • 1
    Possible duplicate of [Check if a file/directory exists: is there a better way?](https://stackoverflow.com/questions/2570930/check-if-a-file-directory-exists-is-there-a-better-way) – EJoshuaS - Stand with Ukraine Oct 02 '18 at 13:46

3 Answers3

1

Use Exists method of DirectoryInfo class to check to check whether directory exists or not.

DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\nour\Desktop\Gedaan");
if(dinfo.Exists)
{
   //your code
}
Sham
  • 910
  • 8
  • 15
1

The file-system can change under your feet, so it's generally better to make an attempt with the file-system and take appropriate corrective measures if you encounter an exception.

So instead of testing with dinfo.Exists then crossing your fingers that the same situation persists on the next few lines, just go ahead and try, then mop up any mess:

DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\nour\Desktop\Gedaan");
FileInfo[] files;
try
{
    files = dinfo.GetFiles("*.DOCX");
}
catch(DirectoryNotFoundException)
{
    Console.WriteLine("ouch");
}

after all, any hardened code will need to catch this exception anyway, even if you believe that some microseconds ago the directory existed.

spender
  • 117,338
  • 33
  • 229
  • 351
0

I think you can just do this:

DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\nour\Desktop\Gedaan");

if (!dinfo.Exists) // <---- check existence here
{
    // your message here
}
else
{
    // rest of your code here...
    FileInfo[] Files = dinfo.GetFiles("*.DOCX");
    foreach (FileInfo file in Files)
    {
        LB2.Items.Add(file.Name);
    }
}
Ojingo
  • 202
  • 2
  • 9