如何检查文件夹中是否存在任何.txt文件?

时间:2015-12-29 03:16:58

标签: c# file

如何检查文件夹中是否存在任何.txt文件?

如果文件夹仍有.txt文件输出错误消息框。

全部!其实我想创建一个函数可以检查文件夹中是否存在任何.txt文件。如果是,则向eventLog写入错误消息。 最后我的代码:

     System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
     DirectoryInfo di = new DirectoryInfo(@"c:/Users/Public/Definitions");
     FileInfo[] TXTFiles = di.GetFiles("*.txt");
     foreach (var fi in TXTFiles)
     {
         if (fi.Exists)
         {
             appLog.Source = "Definitions Folder still have text files";
             appLog.WriteEntry("Still have txt files.");
         }
     }  

3 个答案:

答案 0 :(得分:1)

您可以像这样使用Directory.EnumerateFiles

if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
   Foo();
  

在此处查看更多Directory.EnumerateFiles Method

答案 1 :(得分:1)

您可以查看如下:

DirectoryInfo dir = new DirectoryInfo(@"c:\Directory");
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
    //No files present
}
foreach (var file in TXTFiles)
{
    if(file.Exists)
    {
         //.txt File exists 
    }
}

答案 2 :(得分:0)

你可以这样做

string[] files = System.IO.Directory.GetFiles(path, "*.txt");
if(files.Length >= 1)
{
    MessageBox.Show("Error Message ... Your folder still have some Txt files left");
    // or
    Console.WriteLine("Error Message ... Your folder still have some Txt files left");
}