HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Reading and displaying an image from a folder

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readingimagedisplayingfolderandfrom

Problem

I have a question concerning the correctness of the reading and displaying the image in ASP.NET Core MVC web application.

This is the way I am reading image names from a specific folder (I am using IHostingEnvironment _hostingEnvironment to get the rootPath):

public class GetRandomImageForGalleryView : IGetRandomImageFromFolder
    {
        private string rootPath;
        public GetRandomImageForGalleryView(string rootPath)
        {
            this.rootPath = rootPath;
        }
        public string[] getImage()
        {
            return ReadPhotosFromDirectory();
        }
        private string[] ReadPhotosFromDirectory()
        {

            string[] fileLocations = Directory.GetFiles(rootPath+"\\lib\\Images\\Nature").Select(path => Path.GetFileName(path))
                                     .ToArray();
            return fileLocations;
        }
    }


And this is the way I am displaying them:

@model IGetRandomImageFromFolder
@{ 
    ViewBag.Title = "Gallery";
}

    
        @{
            foreach (var item in Model.getImage())
            {  
                
            }
        }
    


Basically I just replace the image name.

Is this a good way? If not, why? Any other remarks would be helpful as well.

Solution

You could simplify your getImage() method pretty significantly to just:

public IEnumerable GetImage() =>
    Directory.GetFiles(rootPath + @"\lib\Images\Nature").Select(Path.GetFileName);


Things I changed:

  • Changed capitalization to follow .Net naming guidelines.



  • Removed unnecessary method ReadPhotosFromDirectory().



  • Removed unnecessary variable fileLocations.



  • Used verbatim string to avoid having to escape backslashes.



  • Used method group to delegate conversion instead of lambda.



  • Got rid of ToArray(), which didn't serve any purpose, and changed return type to IEnumerable.



  • Used C# 6.0 expression bodied method.

Code Snippets

public IEnumerable<string> GetImage() =>
    Directory.GetFiles(rootPath + @"\lib\Images\Nature").Select(Path.GetFileName);

Context

StackExchange Code Review Q#133616, answer score: 5

Revisions (0)

No revisions yet.