Url request on RichTextBox? - c#

I want to get HTML code to be displayed in a RichTextBox. I am using the code
WebClient client = new WebClient();
byte[] data = client.DownloadData("http://www.google.com");
richTextBox1.Text = data.ToString();
How can I do this?
Also: I don't know why but this shows me "System.Byte[]" on the RichTextBox.

Use WebClient.DownloadString that downloads the specified resource as a String or a Uri:
var contents = new System.Net.WebClient().DownloadString(url);
Note that: RTF encoding is different from HTML. You cannot do this straight away. I suggest WebBrowser control.
or try this ways:
http://www.codeproject.com/KB/HTML/XHTML2RTF.aspx
http://www.codeproject.com/KB/edit/htmlrichtextbox.aspx

It shows System.Byte[] Because it is show the description of data, not data's contents. to do this do something like:
WebClient client = new WebClient();
byte[] file = client.DownloadData("example.com");
File.WriteAllBytes(#"example.txt", file);
string[] lines = File.ReadAllLines("example.txt");
richTextBox1.Text = lines;
To see the actual content
EDIT
Or you can do WebClient.DownloadString like #Ria Suggested. Only I would implement it like this:
WebClient client = new WebClient();
var data = client.DownloadString("example.com");
richTextBox1.Text = data.ToString();
Or to be more efficient even
richTextBox1.Text = client.DownloadString("example.com");

Related

Get json data from url and output as a csv file

How can you get JSON data dynamically, then output it as a CSV file? Is it possible to get it to output with a change in data?
I have the following code below, but it doesn't work.
var url = "https://reqres.in//api/users?page=2";
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
var json = n.DownloadString(url);
string valueOriginal = Convert.ToString(json);
}
I want to get the JSON data from whatever URL and output it as a CSV.
Can you just use CsvHelper? One example can be found from here.
Another option is to write your own implementation to achieve this goal (as shown in example1 or example2).
Good luck.

Using c#, ios to get a JSON address from an API

I am trying to make for example a simple weather app. Mine is for an Air Quality API.
I had this code but I didn't think it would work with JSON.
var webClient = new WebClient();
...
var text = e.Result; // get the downloaded text and store in this variable
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.txt"; // local file to save text in
string localPath = Path.Combine(documentsPath, localFilename); // local path to save file to
File.WriteAllText(localPath, text); // writes to local storage
myTextView.Text = text; // updates the TextView element on the screen with downloaded text data
Then Just
var url = new Uri("https://api.breezometer.com/baqi/?lat=" + latitude + "&lon=" + longitude +"&key=YOUR KEY HERE");
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
Im just not sure of the encoding method for JSON.
If anyone knows please answer thanks...
Use the WebClient class in System.Net:
var json = new WebClient().DownloadString("url");
Origin answer:
How to get a json string from url?

C# encoding Shift-JIS vs. utf8 html agility pack

i have a problem. My goal is to save some Text from a (Japanese Shift-JS encoded)html into a utf8 encoded text file.
But i don't really know how to encode the text.. The HtmlNode object is encoded in Shift-JS. But after i used the ToString() Method, the content is corrupted.
My method so far looks like this:
public String getPage(String url)
{
String content = "";
HtmlDocument page = new HtmlWeb(){AutoDetectEncoding = true}.Load(url);
HtmlNode anchor = page.DocumentNode.SelectSingleNode("//div[contains(#class, 'article-def')]");
if (anchor != null)
{
content = anchor.InnerHtml.ToString();
}
return content;
}
I tried
Console.WriteLine(page.Encoding.EncodingName.ToString());
and got: Japanese Shift-JIS
But converting the html into a String produces the error. I thought there should be a way, but since documentation for html-agility-pack is sparse and i couldn't really find a solution via google, i'm here too get some hints.
Well, AutoDetectEncoding doesn't really work like you'd expect it to. From what i found from looking at the source code of the AgilityPack, the property is only used when loading a local file from disk, not from an url.
So there's three options. One would be to just set the Encoding
OverrideEncoding = Encoding.GetEncoding("shift-jis")
If you know the encoding will always be the same that's the easiest fix.
Or you could download the file locally and load it the same way you do now but instead of the url you'd pass the file path.
using (var client=new WebClient())
{
client.DownloadFile(url, "20130519-OYT1T00606.htm");
}
var htmlWeb = new HtmlWeb(){AutoDetectEncoding = true};
var file = new FileInfo("20130519-OYT1T00606.htm");
HtmlDocument page = htmlWeb.Load(file.FullName);
Or you can detect the encoding from your content like this:
byte[] pageBytes;
using (var client = new WebClient())
{
pageBytes = client.DownloadData(url);
}
HtmlDocument page = new HtmlDocument();
using (var ms = new MemoryStream(pageBytes))
{
page.Load(ms);
var metaContentType = page.DocumentNode.SelectSingleNode("//meta[#http-equiv='Content-Type']").GetAttributeValue("content", "");
var contentType = new System.Net.Mime.ContentType(metaContentType);
ms.Position = 0;
page.Load(ms, Encoding.GetEncoding(contentType.CharSet));
}
And finally, if the page you are querying returns the content-Type in the response you can look here for how to get the encoding.
Your code would of course need a few more null checks than mine does. ;)

Capturing IP address of web stream with StreamReader returning too much data

I have this piece of code:
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead("http://url/getAddress.html");
string text = "";
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
reader.Close();
}
The result of this in HTML is an IP Address, but when i try to save this result in a database, the result that returns is the whole html page of the web request.
What am i doing wrong?
Example:
text has the result
if i do a Response.Write(text); it returns: 111.222.33.3
if i try to save the variable text which returns the value, this will save the whole html content from the web request page.
You realize that if you write to the Response object, that's going to format HTML on the web page? That just formats the HTML you received from the web page. You need to parse the HTML you get to get the actual data you're looking for, in the format you want it.
public static String GetIP()
{
String ip =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
i've found this solution, is perfect for what i want

No response when using WebClient.UploadFile

I'm uploading a file using the UploadFile method on the WebClient object. When the file is uploaded I would like to get a confirmation and according to MSDN (and also here on stackoverflow: Should I check the response of WebClient.UploadFile to know if the upload was successful?) I should be able to read the returned byte array but that is always empty.
Am I doing something the wrong way?
WebClient FtpClient = new WebClient();
FtpClient.Credentials = new NetworkCredential("test", "test");
byte[] responseArray = FtpClient.UploadFile("ftp://localhost/Sample.rpt", #"C:\Test\Sample.rpt");
string s = System.Text.Encoding.ASCII.GetString(responseArray);
Console.WriteLine(s); //Empty string
Or is it always successful if it doesn't return an exception?
Answer to myself: I couldn't make any sense of it so i switched to edt ftp (http://www.enterprisedt.com/) instead.

Categories

Resources