How could I use C# to download the contents of a URL, and store the text in a string, without having to save the file to the hard drive?
The easiest way to download an URL to file or string in C# is using the System.Net.WebClient class. Download URL to file using WebClient class:
The resource to download is specified as a Stringcontaining the URI. DownloadString(Uri) Downloads the requested resource as a String. The resource to download is specified as a Uri. DownloadString(String) Downloads the requested resource as a String.
DownloadString(String) Downloads the requested resource as a String. The resource to download is specified as a Stringcontaining the URI. public: System::String ^ DownloadString(System::String ^ address); public string DownloadString (string address); member this.DownloadString : string -> string
To download a file from a URL, we can use this one-liner: FileUtils.copyURLToFile (new URL (FILE_URL), new File (FILE_NAME), CONNECT_TIMEOUT, READ_TIMEOUT); From a performance standpoint, this code is the same as the one we've exemplified in section 2.
string contents; using (var wc = new System.Net.WebClient()) contents = wc.DownloadString(url);
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