1

Is there a 'correct' way to get the proper web address for a file under an ASP.Net application? For example, I have content in '/Content/Images/Gallery/2010-01-17/small/', and I would like to iterate through all of those files, and output to the browser a link.

Now, I can do it manually by working out the path from the files FullName or I can do it from knowing the current directory, but is there a proper ASP.Net way to do it?

As you can probably tell, I'd rather use the provided method if it exists :)

Regards

Moo

  • Are you looking for the reverse of Server.MapPath? I don't think you can. A URI is mapped to a single file, but a file on the disk can be mapped to multiple URIs. – Kobi Jan 17 '10 at 13:07

2 Answers2

2

You can use the method ResolveUrl() for that. If your content directory is located directly under you web app's root directory, then this should work:

// "~" results in an URL to your web app's root directory
string imageBaseUrl = this.ResolveUrl("~/content/gallery/2010-01-17/small");

Then you can append the names of the images to that base URL.

M4N
  • 94,805
  • 45
  • 217
  • 260
0

I think ResolveUrl is only part of the answer.

Unfortunately, there is not a built-in function to return a full URL to a particular resource, inclusive of hostname and protocol. Part of the reason for this is that you can access a URL any number of ways... and the server is completely agnostic of the hostname. You have to look at either the Request.Url properties to build a new URL from the user's request, or use ServerVariables.

See this question: How to Convert "~/default.aspx" to "http://www.website.com/default.aspx" C#?

Community
  • 1
  • 1
Bryan
  • 8,748
  • 7
  • 41
  • 62