开发者

Any string in some method e.g. File.Exist()

How can I make, in File.Exist method put some filen开发者_如何学Goame that contains some numbers? E.g "file1.abc", "file2.abc", "file3.abc" etc. without using Regex?


Are you trying to determine if various files match the pattern fileN.abc where N is any number? Because File.Exists can't do this. Use Directory.EnumerateFiles instead to get a list of files that match a specific pattern.


Do you mean something like

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


new DirectoryInfo(dir).EnumerateFiles("file*.abc").Any();

or

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


In the unix world, it is called globbing. Maybe you can find a .NET library for that? As a starting point, check out this post: glob pattern matching in .NET


Below is the code snap which will return all files with name prefix "file" with any digits whose format looks like "fileN.abc", even it wont return with file name "file.abc" or "fileX.abc" etc.

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();

Hope this would be very helpful, thanks for your time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜