在C#中打印HTML,可以使用以下方法:
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient();
var response = await client.GetAsync("https://www.example.com");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
using System.Net;
class Program
{
static void Main(string[] args)
{
using var client = new WebClient();
var content = client.DownloadString("https://www.example.com");
Console.WriteLine(content);
}
}
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
var web = new HtmlWeb();
var htmlDoc = web.Load("https://www.example.com");
Console.WriteLine(htmlDoc.DocumentNode.OuterHtml);
}
}
using System.Net;
using System.Net.Http.Headers;
using System.Text;
class Program
{
static void Main(string[] args)
{
using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
var context = listener.GetContext();
var response = context.Response;
var html = "<html><body><h1>Hello, World!</h1></body></html>";
var buffer = Encoding.UTF8.GetBytes(html);
response.ContentLength64 = buffer.Length;
response.ContentType = "text/html";
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
}
以上是在C#中打印HTML的常见方法,可以根据实际需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云