Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a Set of File Paths Using a Regular Expression

Can I do one read to disk with a regular expression instead of doing this three times?

var path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.png", id)); 

if (!File.Exists(path))
{
    path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.jpg", id));

    if (!File.Exists(path))
    {
        path = HttpContext.Current.Server.MapPath(string.Format("~/Assets/Images/{0}.gif", id));
like image 270
Mike Flynn Avatar asked Jul 18 '13 20:07

Mike Flynn


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

Can you use regex in XML?

You can define regular expressions for input validation in separate XML files. Reference to these regular expressions can be used in multiple data types that are defined in the datatypes. xml file.

What is regular expression in UiPath?

Regular Expressions, or RegEx, is a sequence of characters that defines a search pattern. As a UiPath RPA Developer, we use RegEx to extract data out of, e.g., emails and PDFs. Learning is necessary, as RPA is about extracting data from one system and placing them in another.


2 Answers

Assuming you don't care which you hit:

using System.IO

string imagesPath = HttpContext.Current.Server.MapPath("~/Assets/Images");
string path = null;
foreach (var filePath in Directory.GetFiles(imagesPath, id + ".*"))
{
    switch (Path.GetExtension(filePath))
    {
       case ".png":
       case ".jpg":
       case ".gif":
           path = filePath;
           break;
    }
}

If path is not null you found one.

like image 176
Guvante Avatar answered Sep 20 '22 01:09

Guvante


Try something like this (only works in .NET4 and after):

string folder = HttpContext.Current.Server.MapPath("~/Assets/Images/");
string[] extensions = { ".jpg", ".gif", ".png" };
bool exists = Directory.EnumerateFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                 .Any(f => extensions.Contains(Path.GetExtension(f)));
like image 36
sean717 Avatar answered Sep 22 '22 01:09

sean717