Search code examples
c#asp.netgetdirectories

How to properly list files of a directory?


I was using below code until I get too many images. So I wanted to make a method in the master page cs file class to rather generate the HTML for me.

<img src="<%= ResolveUrl("~/images/1.png") %>">

But as long I get a lot of images I wrote this method to generate the HTML:

public void GenerateSlideItems()
        {
            string[] files = Directory.GetFiles(Server.MapPath("~/images"));
            foreach(string file in files)
            {
                string filename = Path.GetFileNameWithoutExtension(file);
                Response.Write(string.Format(
                                            "<img src=\"{0}\"  class=\"img-responsive\" alt=\"{1}\">",
                                            file, filename));
            }
        }

But I'm getting the images like C:\...\visual studio\project\etc\1.png rather http:\\localhost:5090\images\1.png how do I do that? I also tried with and without ResolveUrl() but it ended up returning something like C:\images\1.png which obviously isn't the correct path I'm looking for. I new to ASP.NET I don't know yet how those things are usually done. I'm learning.


Solution

  • Basically, you have to look back at what you were originally doing and replicate the functionality:

    ResolveUrl("~/images/1.png")
    

    You have a server-side file system path, and you need to turn it into a URL. Since file contains the file name, and you have a hard-coded path from where you got the files, you should be able to combine those values:

    var root = "~/images"
    string[] files = Directory.GetFiles(Server.MapPath(root));
    foreach (var file in files)
    {
        var filename = Path.GetFileName(file);
        var filenameWithoutExtension = Path.GetFileNameWithoutExtension(file);
    
        var serverUrl = string.Format("{0}/{1}", root, filename);
        var browserUrl = ResolveUrl(serverUrl);
        // now you should be able to use browserUrl in your manually-built HTML...
    
        Response.Write(string.Format(
                                    "<img src=\"{0}\" class=\"img-responsive\" alt=\"{1}\">",
                                    browserUrl, filenameWithoutExtension));
    }
    

    The reason for the extra step in turning the "server URL" to a "browser URL" is because the ~ path won't mean anything to a browser. And since you're manually writing this HTML to the response, the framework never has a chance to translate that path for you.