2015-07-10 44 views
-3

这些文件夹C#中存在不允许的文件

  • file1.exe
  • file2.dll

我想看看是此文件夹中存在多余的文件。例如,如果我在此文件夹中创建examplefile.exe它必须给我一个错误,必须只有上面列出的那些文件。所以我创建了需要的文件字符串:

string[] only_these_files = { 
    "file1.exe", 
    "file2.dll" 
}; 

现在我需要搜索无关的文件,但如何?立即感谢。

我试过这段代码,但我不知道如何检查它。

string[] only_these_files = { 
      "image1.png", 
      "image2.png", 
      "image3.png", 
      "image4.png", 
      "image5.png" 
     }; 
     string[] fileEntries = Directory.GetFiles(@"C:\Users\Dewagg\Desktop\test\"); 

     List<String> badFiles = new List<string>(); 

     foreach (string fileName in fileEntries) 
      if (!only_these_files.Contains(fileName)) 
      { 
       badFiles.Add(fileName); 
      } 
+2

不要问社会编写代码为您服务。寻求帮助来解决你自己的代码。 – oppassum

+1

将问题分解成部分,然后回到这里,用你不知道该怎么做的特定部分:1)获取文件夹中所有文件的列表2)查看文件列表中的任何文件是否不是允许的两个文件3)向用户报告错误消息。 –

+0

'我试过这段代码,但是我不知道如何检查它。':你是什么意思? – sstan

回答

1

这不完全火箭科学:像这样的你:

HashSet<string> allowedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase) 
{ 
    "file1.exe" , 
    "file2.dll" , 
}; 
DirectoryInfo directory = new DirectoryInfo(@"c:\foo\bar") ; 

bool containsNonAllowedFiles = directory 
           .EnumerateFiles(@"C\foo\bar") 
           .Any(fi => !allowedFiles.Contains(fi.Name)) 
           ; 
bool containsAllAllowedFiles = allowedFiles 
           .All(fn => directory.EnumerateFiles(fn).Any()) 
           ; 
+0

谢谢,它为我工作 – Dewagg

0

试试这个,因为你只需要检查两个文件,它是一个不好的编码约定使用ArrayList的你在做什么,顺便说一句

try{ 
    if (!File.Exists("TextFile1.txt")) 
    throw new FileNotFoundException(); 
} 
catch(FileNotFoundException e) 
{ 
    // your message here. 
} 
+0

根据我的理解,OP不只是想检查文件是否存在,而是要确保该目录中没有任何其他文件。 – Speerian

+0

'System.IO.Directory myDir = GetMyDirectoryForTheExample(); int count = myDir.GetFiles()。Length;'然后他可以检查计数是2 –

+0

我宁愿看到一个列表然后直接比较一系列单个项目的任何一天...它可以被扩展。 –

4

如果你想检查你的代码,然后你总是可以在其中放置一个断点并观察执行情况。您需要在桌面上创建文件,以便了解预期结果。

如果你想验证没有任何错误的文件,那么你可以检查坏文件列表的大小。

所以,你想要的东西,如:

if(badFiles.Count>0)//based off your sample code with png's 
{ 
    //notify user 
    MessageBox.Show("Bad files were found"); //or create anonymous function to display bad files 
    // or Console.WriteLine("Bad files were found"); 
} 
+0

.....为什么'> 5'? – sstan

+0

@sstan好赶,没有读通过他的所有代码 – Speerian

+0

非常感谢你;) – Dewagg