某些方法中的任何字符串,例如 File.Exist()

本文关键字:File 例如 Exist 字符串 方法 任何 | 更新日期: 2023-09-27 17:55:11

如何在File.Exist方法中放置一些包含一些数字的文件名?例如,"file1.abc"、"file2.abc"、"file3.abc"等,而不使用正则表达式?

某些方法中的任何字符串,例如 File.Exist()

您是否正在尝试确定各种文件是否与模式匹配fileN.abc N是任何数字?因为File.Exists做不到这一点。请改用 Directory.EnumerateFiles 来获取与特定模式匹配的文件列表。

你的意思是像

for (int i = 1; i < 4; i++)
{
    string fileName = "file" + i.ToString() + ".abc";
    if (File.Exists(fileName))
    {
        // ...
    }
}
new DirectoryInfo(dir).EnumerateFiles("file*.abc").Any();

Directory.EnumerateFiles(dir, "file*.abc").Any();

在 unix 世界中,它被称为通配。也许你可以为此找到一个 .NET 库?作为起点,请查看这篇文章:.NET 中的 glob 模式匹配

下面是代码快照,它将返回所有名称前缀为"file"的文件,其格式看起来像"fileN.abc"的任何数字,即使它不会返回文件名"file.abc"或"fileX.abc"等。

List<string> str = 
    Directory.EnumerateFiles(Server.MapPath("~/"), "file*.abc")
      .Where((file => (!string.IsNullOrWhiteSpace( 
             Path.GetFileNameWithoutExtension(file).Substring( 
             Path.GetFileNameWithoutExtension(file).IndexOf(
              "file") + "file".Length))) 
            &&  
            (int.TryParse(Path.GetFileNameWithoutExtension(file).Substring( 
                Path.GetFileNameWithoutExtension(file).IndexOf("file") + "file".Length), 
                out result) == true))).ToList();

希望这会很有帮助,感谢您的时间。