How to read a file from a URI using StreamReader?

前端 未结 3 659
野的像风
野的像风 2020-12-06 20:20

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

相关标签:
3条回答
  • 2020-12-06 20:50

    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");
    
    0 讨论(0)
  • 2020-12-06 21:00

    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();
    
    0 讨论(0)
  • 2020-12-06 21:02

    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())
        ...
    
    0 讨论(0)
提交回复
热议问题