Search code examples
c#asp.netresponse.write

Response.WriteFile with a URL possible?


I would like to be able to do this:

Response.WriteFile ("http://domain/filepath/file.mpg")

But, I get this error:

Invalid path for MapPath 'http://domain/filepath/file.mpg' 
A virtual path is expected.

The WriteFile method does not appear to work with URLs. Is there any other way I can write the contents of a URL to my page?

Thanks.


Solution

  • If you need the code to work in that manner, then you will have to dynamically download it onto your server first:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://domain/filepath/file.mpg");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream file = response.GetResponseStream();
    

    From that point, you have the contents of the file as a stream, and you will have to read/write the bytes out to the response.

    I will mention however, that this is not necessarily optimal--you will be killing your bandwidth, because every file will be using far more resources than necessary.

    If possible, move the file to your server, or rethink exactly what you are trying to do.