如果存在不允许的文件,则显示带有其名称的消息框

本文关键字:消息 显示 不允许 存在 文件 如果 | 更新日期: 2023-09-27 18:02:57

我有这样的代码:

HashSet<string> allowedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
      "file1.dll",
      "file2.dll",
      "file3.exe"
};
DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
bool containsNonAllowedFiles = directory.EnumerateFiles().Any(file => !allowedFiles.Contains(file.Name));
if (containsNonAllowedFiles == true)
{
     Message.Warning("Unallowed files found ! Please remove them."); 
     return; 
}

但是我想显示文件名,这是不允许的,我该怎么做?

例如我有这些文件文件夹:file1.dll, file2.dll, file3.exe, file4.exe,当我启动应用程序时,它必须为我打印不允许的文件发现!请删除file4.exe并重新启动应用程序。提前感谢

如果存在不允许的文件,则显示带有其名称的消息框

使用Linq中的Except方法生成不允许的文件名列表。

var disallowedFiles = directory.EnumerateFiles()
                               .Select(fi => fi.Name)
                               .Except(allowedFiles, StringComparer.OrdinalIgnoreCase)
                               .ToList();
        DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
        List<FileInfo> files = directory.GetFiles().ToList();
        List<FileInfo> unAllowed = files.FindAll(f => !allowedFiles.Contains(f.Name));
        if (unAllowed.Count > 0)
        {
            string notAllowedFiles = "";
            unAllowed.ForEach(f => notAllowedFiles += f.Name + ",");
            Message.Warning("Unallowed files found ! Please remove " + notAllowedFiles);
            return;
        }

您可以使用Where代替早期的Any:

var nonAllowedFilesNames = directory.EnumerateFiles()
    .Select(file => file.Name)
    .Where(fileName => !allowedFiles.Contains(fileName));
if(nonAllowedFilesNames.Any())
{
     string unallowedFiles = String.Join(",", nonAllowedFilesNames);
     Message.Warning("Unallowed files found ! Please remove: " + unallowedFiles); 
}

您必须获得不允许的文件列表。你可以这样做:

List<String> nonAllowedFiles = directory.EnumerateFiles().FindAll(file => !allowedFiles.Contains(file.Name));

然后你可以这样处理:

foreach (String file in nonAllowedFiles ) {
    Message.Warning("Unallowed files found ! Please remove " + file + " and start app again"); 
}
return;