Как загрузить HTML документ на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите HTML-документ из файла или потока.
  1. Загрузить из файла:
    
    DocumentCore dc = DocumentCore.Load(@"d:\Book.html");
    
    Объект dc представляет собой документ, загруженный в память. Формат файла определяется автоматически по расширению файла: ".html".

    После загрузки Вы получите документ, представленный в виде Tree Of Objects, где корневым узлом является класс DocumentCore.

    Чтобы гарантировать, что загружаемый контент действительно является HTML, и установить некоторые параметры загрузки, используйте HtmlLoadOptions в качестве второго параметра.

    
    DocumentCore dc = DocumentCore.Load(@"d:\Book.html", new HtmlLoadOptions());
    
  2. Загрузить с использованием памяти:
    
                // Let us say we already have a HTML document as array of bytes.
                DocumentCore dc = null;
                using (MemoryStream htmlStream = new MemoryStream(htmlBytes))
                {
                    dc = DocumentCore.Load(htmlStream, new HtmlLoadOptions());
                }
                // Here we can do with our document 'dc' anything we need.
    

Полный код

using System;
using System.IO;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
        
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            LoadHtmlFromFile();
            //LoadHtmlFromStream();
        }

        /// <summary>
        /// Loads an HTML document into DocumentCore (dc) from a file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-html-document-net-csharp-vb.php
        /// </remarks>
        static void LoadHtmlFromFile()
        {
            string filePath = @"..\..\..\example.html";
            // The file format is detected automatically from the file extension: ".html".
            // But as shown in the example below, we can specify HtmlLoadOptions as 2nd parameter
            // to explicitly set that a loadable document has HTML format.
            DocumentCore dc = DocumentCore.Load(filePath);
            if (dc != null)
                Console.WriteLine("Loaded successfully!");

			Console.ReadKey();			
        }

        /// <summary>
        /// Loads an HTML document into DocumentCore (dc) from a MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-html-document-net-csharp-vb.php
        /// </remarks>
        static void LoadHtmlFromStream()
        {
            // Get document bytes.
            byte[] fileBytes = File.ReadAllBytes(@"..\..\..\example.html");

            DocumentCore dc = null;

            // Create a MemoryStream
            using (MemoryStream ms = new MemoryStream(fileBytes))
            {
                // Load a document from the MemoryStream.
                // Specifying HtmlLoadOptions we explicitly set that a loadable document is HTML.
                dc = DocumentCore.Load(ms, new HtmlLoadOptions());
            }
            if (dc != null)
                Console.WriteLine("Loaded successfully!");
			
			Console.ReadKey();			
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        LoadHtmlFromFile()
        'LoadHtmlFromStream();
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Loads an HTML document into DocumentCore (dc) from a file.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-html-document-net-csharp-vb.php
    ''' </remarks>
    Sub LoadHtmlFromFile()
        Dim filePath As String = "..\..\..\example.html"
        ' The file format is detected automatically from the file extension: ".html".
        ' But as shown in the example below, we can specify HtmlLoadOptions as 2nd parameter
        ' to explicitly set that a loadable document has HTML format.
        Dim dc As DocumentCore = DocumentCore.Load(filePath)
        If dc IsNot Nothing Then
            Console.WriteLine("Loaded successfully!")
        End If
		
		Console.ReadKey()
    End Sub

    ''' <summary>
    ''' Loads an HTML document into DocumentCore (dc) from a MemoryStream.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-html-document-net-csharp-vb.php
    ''' </remarks>
    Sub LoadHtmlFromStream()
        ' Get document bytes.
        Dim fileBytes() As Byte = File.ReadAllBytes("..\..\..\example.html")

        Dim dc As DocumentCore = Nothing

        ' Create a MemoryStream
        Using ms As New MemoryStream(fileBytes)
            ' Load a document from the MemoryStream.
            ' Specifying HtmlLoadOptions we explicitly set that a loadable document is HTML.
            dc = DocumentCore.Load(ms, New HtmlLoadOptions())
        End Using
        If dc IsNot Nothing Then
            Console.WriteLine("Loaded successfully!")
        End If
		
		Console.ReadKey()		
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.