locked
how to retrive the all the image from the folder in C# RRS feed

  • Question

  • User-1722422105 posted

    Hi 

     i am creating web api for displaying the all images from the folder haveing images

     below is my code, but it displaying the last image from the folder.


    HttpResponseMessage Response = new HttpResponseMessage(HttpStatusCode.OK);

    string[] filesindirectory = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images"));
    List<String> images = new List<string>(filesindirectory.Count());

    foreach (string item in filesindirectory)
    {

    images.Add(String.Format("~/images", System.IO.Path.GetFileName(item)));
    byte[] fileData = File.ReadAllBytes(item);
    Response.Content = new ByteArrayContent(fileData);

    }

    Response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return Response;

    Wednesday, June 6, 2018 9:40 AM

All replies

  • User61956409 posted

    Hi sidu,

    sidu

    it displaying the last image from the folder

    In your code, we can find that Response.Content will be assigned with new ByteArrayContent per iteration in your foreach loop, so the final Response.Content is  assigned with the ByteArrayContent of the last image.

    sidu

    creating web api for displaying the all images

    Your requirement is retrieving and displaying all images, if possible, you can modify your approach and code logic to return a list of images info (folder+imagename) to frontend application, then the frontend application can traverse the returned images list and make another request to access each image contained in that list. On the other hand if the folder/images could be publicly accessible, you can make the webapi return a list that contains URLs to these images.

    With Regards,

    Fei Han

    Thursday, June 7, 2018 3:12 AM