1.เมธอดของ WebClient ที่ใช้ในการดาวน์โหลด
2.เมธอดของ WebClient ที่ใช้ในการอัพโหลด
1.เมธอดของ WebClient ที่ใช้ในการดาวน์โหลด
C# มี WebClient ไว้ช่วยดาวน์โหลด HTML source มาบันทึกเป็นไฟล์ หรือเป็น string ได้
using System;
using System.Net;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
string url = "https://phaisarn.com/";
//---Download file
client.DownloadFile(url, @"localfile.html");
//---Download string
string htmlCode1 = client.DownloadString(url);
Console.WriteLine(htmlCode1.Substring(0, 100));
Console.WriteLine();
//---Download data
byte[] myDataBuffer = client.DownloadData(url);
// Convert the downloaded data into a string
string htmlCode2= Encoding.ASCII.GetString(myDataBuffer);
Console.WriteLine(htmlCode2.Substring(0, 100));
Console.WriteLine();
Console.WriteLine("Download successful.");
}
}
}
}
ถ้าเจอ error ว่า The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
ให้ ignore ด้วย
// วางบรรทัดนี้ก่อนเรียก client ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; client.DownloadFile(url, localFile);
2.เมธอดของ WebClient ที่ใช้ในการอัพโหลด
ส่งค่าไปด้วยเว็บเมธอด POST (เป็นการ POST โดยไม่มีการ redirect ไปไหน)
ถ้าต้องการให้ POST พร้อม redirect ใช้ JavaScript
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string url = "https://phaisarn.com/";
try
{
WebClient client = new WebClient();
// Download the data to a file.
client.DownloadFile(url, "page.htm");
// Download the data to a buffer.
Byte[] pageData = client.DownloadData("http://www.contoso.com");
string pageHtml = Encoding.ASCII.GetString(pageData);
Console.WriteLine(pageHtml);
// Upload some form post values.
NameValueCollection form = new NameValueCollection();
form.Add("MyName", "MyValue");
Byte[] responseData = client.UploadValues(url, form);
// Decode and display the response.
Console.WriteLine("\nResponse received was :\n{0}", Encoding.ASCII.GetString(responseData));
}
catch (WebException webEx)
{
Console.WriteLine(webEx.ToString());
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
}
}
ถ้าต้องการให้ redirect ใช้คำสั่ง
Response.Redirect("http://www.google.com");