如果是,则DirectoryInfo

时间:2018-10-02 13:32:48

标签: c# wpf

我使用DirectoryInfo从文件夹中获取文件。

但可以说该文件夹的目录不存在

我要显示一条消息(“找不到目录”)

<?php

  $xml = file_get_contents('note.xml');
  $dom = new DOMDocument();
  $dom->loadXML($xml);

    foreach ($dom->getElementsByTagName('standard') as $standard){

    $mechdescription = $standard->getElementsByTagName('description')->item(0)->nodeValue;
    $mecharray[] = $mechdescription;

   }
    foreach ($mecharray as $displaymech){

     echo $displaymech."<br>";

   }

 ?>

3 个答案:

答案 0 :(得分:1)

使用Exists类的DirectoryInfo方法检查目录是否存在。

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

答案 1 :(得分:1)

文件系统可以在您的脚下改变,因此通常最好尝试使用文件系统,并在遇到异常时采取适当的纠正措施。

因此,不要用dinfo.Exists进行测试,而是用手指指着接下来的几行仍然存在相同的情况,只需继续尝试,然后清除所有混乱:

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

毕竟,即使您相信该目录存在几微秒之前,任何经过强化的代码仍然需要捕获此异常。

答案 2 :(得分:0)

我认为您可以这样做:

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);
    }
}