Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file from a URI using StreamReader?

Tags:

c#

I have a file at a URI that I would like to read using StreamReader. Obviously, this causes a problem since File.OpenText does not support URI paths. The file is a txt file with a bunch of html in it. I have multiple web pages that use this same piece of html, so I have put it in a txt file, and am reading it into the page when the page loads (I can get it to work when I put the file on the file system, but need to put it in a document repository online so that a business user can get to it). I am trying to avoid using an iframe. Is there a way to use StreamReader with URI formats? If not, what other options are there using C# to read in the txt file of html? If this is not optimal, can someone suggest a better approach?

like image 672
Josh Avatar asked Aug 11 '10 16:08

Josh


3 Answers

Is there a specific requirement to use StreamReader? Unless there is, you can use the WebClient class:

var webClient = new WebClient();
string readHtml = webClient.DownloadString("your_file_path_url");
like image 56
Yakimych Avatar answered Oct 20 '22 15:10

Yakimych


You could try using the HttpWebRequestClass, or WebClient. Here's the slightly complicated web request example. It's advantage over WebClient is it gives you more control over how the request is made:

HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(lcUrl);

httpRequest.Timeout = 10000;     // 10 secs
httpRequest.UserAgent = "Code Sample Web Client";

HttpWebResponse webResponse = (HttpWebResponse) httpRequest.GetResponse();
StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());

string content = responseStream.ReadToEnd();
like image 26
LBushkin Avatar answered Oct 20 '22 15:10

LBushkin


If you are behind a proxy don't forget to set your credentials:

  WebRequest request=WebRequest.Create(url);
  request.Timeout=30*60*1000;
  request.UseDefaultCredentials=true;
  request.Proxy.Credentials=request.Credentials;
  WebResponse response=(WebResponse)request.GetResponse();
  using (Stream s=response.GetResponseStream())
    ...
like image 45
laktak Avatar answered Oct 20 '22 16:10

laktak