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));
$ 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.
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.
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.
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With