Home > OS >  Selecting a specifik directory depending on its name as compared to the Id of an article item
Selecting a specifik directory depending on its name as compared to the Id of an article item

Time:09-28

I´m working on a personal side project, a web store, as an ASP.Net Core application with C#.

I'm trying to create an ImageHandler service that is to be used for fetching images that are located in a folder in the project.

I´m trying to structure the images so that they are easy to manage in the project with code, and to be easily overseeable, so I created a bunch of subfolders/directories.

The path looks like this:

WebRoot/Images/Articles/ArticleFolder/ArticleImages.jpg

The Article folder is named Article.id_Article.Name so a complete example would be:

 \wwwroot\Images\Articles\1_iPhone 13 Pro Max – 5G smartphone 128GB Silver\1_01.jpg.

I'm trying to write a statement that finds the right folder for a given article by making a selection on the first part of the folder name that is equal to the ID of the article it belongs to.

My first attempt looked like this:

var path = Path.Combine(Enviroment.WebRootPath, "Images", "Articles");
string dir = Directory.GetDirectories(path).First(d => Path.GetFileName(d).StartsWith(articleId.ToString())); 

But if I where looking for a image with the id of 1, the line would give me a directory starting with 10_article.Name so obviously that wouldn't do.

I then tried:

string dir2 = Directory.GetDirectories(path).First(d => Path.GetFileName(d).Where(d => d.Split('_')[0] == articleId.ToString()));

I thought that would work, but I'm getting an error on the d.Split('_')[0]. It claims that d is now an char and therefore the method split can't be used. I understand that you somehow can save images as binary data in a SQL database and to keep images in the project folder might be dumb, as is my naming convention, but I'm curious how you could solve this. Any insight?

CodePudding user response:

As I understand it, your structure is "/webroot/Images/Articles" (which remains constant), combined with /{articleId} "_" {articleName}/{imageName}, where the items in curly braces are variable, correct? How about something like this?

string imageRootFolder = Path.Combine(Enviroment.WebRootPath, "Images", "Articles");
string articleDir = Directory.GetDirectories(imageRootFolder).Where(dir => dir.StartsWith(articleId.ToString()   "_")).First();
List<string> pathsToImages = Directory.GetFiles(Path.Combine(imageRootFolder, articleDir)).ToList();
  • Related