1. DNS使用
DNS类是一个静态类,提供从网络上获取特定主机的信息。
//通过主机名获取域名
IPHostEntry host = Dns.GetHostEntry(textBox1.Text);
Label1.Text = host.HostName;
//通过主机名获取IP
IPHostEntry host = Dns.GetHostEntry(textBox1.Text);
Label2.Text = host.AddressList[1].ToString();
2. WebClient使用
WebClient提供从指定的URL上获取资源或向其发送数据。
(1) WebClient从网络上获取数据
WebClient client = new WebClient();
//textBox1.Text一个URL
Streamstream = client.OpenRead(textBox1.Text);
intbyteCount = 0;
do
{
byteCount=stream.ReadByte();
if(byteCount>0)
richTextBox1.Text+=Convert.ToChar(byteCount);
} while(byteCount>0);
stream.Close();
(2) 下载文件
WebClient client = new WebClient();
FolderBrowserDialogdlg = new FolderBrowserDialog();
if(dlg.ShowDialog()==DialogResult.OK)
{
stringpath = dlg.SelectedPath+"\\" +
//文件存放的位置
Path.GetFileName(textBox2.Text);
client.DownloadFile(textBox2.Text,path);
}
3. WebRequest和WebResponse
分别为向指定的URL发送请求和接受应答的类。
WebRequest request = WebRequest.Create(textBox1.Text);
WebResponseresponse = request.GetResponse();
Streamstream = response.GetResponseStream();
//编码方式任意
Encodingencode = Encoding.GetEncoding("utf-8");
StreamReaderreader = new StreamReader(stream,encode);
Char[]buffer = new Char[100];
intcount = reader.Read(buffer, 0, 100);
while(count > 0)
{
stringstr = new string(buffer,0, 100);
richTextBox1.Text += str;
count = reader.Read(buffer, 0, 100);
}