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.
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.
Try this:
HttpContext.Current.Server.MapPath("~/images");
Hope that helps
You have the base path for your website: Server.MapPath("~");
So replace Server.MapPath("~")
with your domain name on all your image paths.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.