我有一个列表,列出了我想要针对已批准的扩展程序列表的文件。 已批准的扩展名列表可以是
我需要处理两个案例
一直尝试使用正则表达式,因为某些情况可以组合在一起。例如,.docx
和.doc
被视为相同的
这是我到目前为止(伪代码)
List<string[]> approvedExt = new List<string[]>();
// M - Mandatory
// O - Optional
approvedExt.Add(new[] { "pdf", "M" });
approvedExt.Add(new[] { "(docx|doc)", "M" }); //Handle as one case
approvedExt.Add(new[] { "(txt)", "O" });
//Example list
List<string> fileList = new List<string>();
fileList.Add("123.pdf");
fileList.Add("123.txt");
fileList.Add("123.xlsx");
fileList.Add("123.pdf");
//pseudo code
For each ext in approvedExt (that are Mandatory)
{
bool checkMandatoryExt = Any file match?
//Example code I have seen
fileList.All(f => System.Text.RegularExpressions.Regex.IsMatch(f, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase));
}
if (!checkMandatoryExt)
{
//Handle Error
}
for each file in fileList
{
bool allApprovedExt = Any patterns match?
}
if (!allApprovedExt)
{
//Handle Error
}
上面的示例文件列表将失败2个案例
.xlsx
文件(不在批准的分机列表中).docx
也不包含.doc
文件(强制扩展名不在文件列表中)如果列表文件通过上述两项检查,我希望能够传递文件名列表和已批准的扩展名列表并返回true
/ false
。
谢谢
答案 0 :(得分:2)
以下是我将如何解决它(伪代码):
public class Condition
{
public bool Mandatory {get;set;}
public string[] Extensions {get;set;}
}
// ...
//NOTE: includes the . before the extension
public string[] GetExtensions(IEnumerable<string> files)
{
return files.Select(f => Path.GetExtension(f).ToLower()??"").Distinct().ToArray();
}
public bool AllConditionsOk(string[] fileNamesToCheck, Condition[] conditions)
{
//Extract Extension only (e.g. Path.GetExtension)
string[] extensions = GetExtensions(fileNamesToCheck);
//Check if any existing extension is not allowed
foreach(string extension in extensions)
{
if(!conditions.Any(c => c.Extensions.Contains(extension)))
return false;
}
//Check if every mandatory condition is fulfilled
foreach(Condition condition in conditions.Where(c => c.Mandatory))
{
if(!condition.Extensions.Any(e => extensions.Contains(e)))
return false;
}
return true;
}
或者如果你喜欢短版本:
return extensions.Any(extension => !conditions.Any(c => c.Extensions.Contains(extension))) &&
conditions.Where(c => c.Mandatory)
.All(condition => condition.Extensions.Any(e => extensions.Contains(e)));
答案 1 :(得分:0)
如果您需要检查扩展名列表中文件名列表中包含的扩展程序,您可以这样做:
foreach(var file in filelist)
{
approvedExt.Contains(file.split(".").Last();
}