tags:

views:

241

answers:

2

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?

+4  A: 
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.

Mehrdad Afshari
Interesting... I wouldn't have expected it to work with file://... the only other one I'd be vaguely interested in at the moment is ftp://, but that's not likely.
Matthew Scharley
Oh, I missed it.. It does work for ftp:// too.
Mehrdad Afshari
+4  A: 

The easiest way is by using the WebClient class:

WebClient client = new WebClient();

string contents = client.DownloadString(uri);
Philippe Leybaert
Sadly, it's not thread-safe, which is an issue, and from what I can see from a quick glance, it only supports HTTP (I need atleast file:// too)
Matthew Scharley
@Matthew: Internally, it just uses `WebRequest` so it supports file:// and ftp:// too. If you need more control, you should use `WebRequest` directly. If you just want a string back, use `WebClient`.
Mehrdad Afshari
It does support other URIs. It's not limited to HTTP. And what do you mean by not being thread-safe?
Philippe Leybaert
If you need multiple threads - use multiple `WebClient` instances. There is no thread safety issue here...
Marc Gravell
Good point Marc
Matthew Scharley