How to read a file from internet?

后端 未结 7 1907
甜味超标
甜味超标 2020-12-03 03:05

simple question: I have an file online (txt). How to read it and check if its there? (C#.net 2.0)

7条回答
  •  日久生厌
    2020-12-03 03:28

    an alternative to HttpWebRequest is WebClient

        // create a new instance of WebClient
        WebClient client = new WebClient();
    
        // set the user agent to IE6
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        try
        {
            // actually execute the GET request
            string ret = client.DownloadString("http://www.google.com/");
    
            // ret now contains the contents of the webpage
            Console.WriteLine("First 256 bytes of response: " + ret.Substring(0,265));
        }
        catch (WebException we)
        {
            // WebException.Status holds useful information
            Console.WriteLine(we.Message + "\n" + we.Status.ToString());
        }
        catch (NotSupportedException ne)
        {
            // other errors
            Console.WriteLine(ne.Message);
        }
    

    example from http://www.daveamenta.com/2008-05/c-webclient-usage/

提交回复
热议问题