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?
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.
The easiest way is by using the WebClient class:
using(WebClient client = new WebClient())
{
string contents = client.DownloadString(uri);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With