Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to open a Uri and get whatever it points to? (C#)

Tags:

c#

uri

I have a Uri object being passed to a constructor of my class.

I want to open the file the Uri points to, whether it's local, network, http, whatever, and read the contents into a string. Is there an easy way of doing this, or do I have to try to work off things like Uri.IsFile to figure out how to try to open it?

like image 988
Matthew Scharley Avatar asked Jul 01 '09 10:07

Matthew Scharley


2 Answers

static string GetContents(Uri uri) {
    using (var response = WebRequest.Create(uri).GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream))
        return reader.ReadToEnd();
}

It won't work for whatever. It works for file://, http:// and https:// and ftp:// by default. However, you can register custom URI handlers with WebRequest.RegisterPrefix to make it work for those as well.

like image 99
mmx Avatar answered Sep 21 '22 06:09

mmx


The easiest way is by using the WebClient class:

using(WebClient client = new WebClient())
{
    string contents = client.DownloadString(uri);
}
like image 29
Philippe Leybaert Avatar answered Sep 23 '22 06:09

Philippe Leybaert