Click here to Skip to main content
11,923,517 members (67,110 online)
Click here to Skip to main content
Add your own
alternative version


159 bookmarked

Convert any URL to a MHTML archive using native .NET code

, 3 Apr 2005
Rate this:
Please Sign up or sign in to vote.
A native .NET class for saving URLs: text-only, HTML page, HTML archive, or HTML complete.

Sample Image - MhtBuilder.gif


If you've ever used the File | Save As... menu in Internet Explorer, you might have noticed a few interesting options IE provides under the Save As Type drop-down box:

Screenshot - Internet Explorer Save As menu

The options provided are:

  • Web Page, complete
  • Web Archive, single file
  • Web Page, HTML only
  • Text File

Most of these are self-explanatory, with the exception of the Web Archive (MHTML) format. What's neat about this format is that it bundles the web page and all of its references, into a single compact .MHT file. It's a lot easier to distribute a single self-contained file than it is to distribute a HTML file with a subfolder full of image/CSS/Flash/XML files referenced by that HTML file. In our case, we were generating HTML reports and we needed to check these reports into a document management system which expects a single file. The MHTML (*.mht) format solves this problem beautifully!

This project contains the MhtBuilder class, a 100% .NET managed code solution which can auto-generate a MHT file from a target URL, in one line of code. As a bonus, it will also generate all the other formats listed above, too. And it's completely free, unlike some commercial solutions you might find out there.


I know people assume the worst of Microsoft, but the MHTML format is actually based on RFC standard 2557, compliant Multipart MIME Message (MHTML web archive). So it's an actual Internet standard! Web Archive, a.k.a. MHTML, is a remarkably simple plain text format which looks a lot like (and is in fact almost exactly identical to) an email. Here's the header of the MHT file you are viewing at the top of the page:

Screenshot - Mht file header

To generate a MHTML file, we simply merge together all of the files referenced in the HTML. The red line marks the first content block; there will be one content block for each file. We need to follow a few rules, though:

  • Use Quoted-Printable encoding for the text formats.
  • Use Base64 encoding for the binary formats.
  • Make sure the Content-Location has the correct absolute URL for each reference.

Not all websites will tolerate being packaged into a MHTML file. This version of Mht.Builder supports frames and IFrame, but watch out for pages that include lots of complicated JavaScript. You'll want to use the .StripScripts option on sites like that.

Using Mht.Builder

MhtBuilder comes with a complete demo app:

Screenshot - Mht demo application

Try it out on your favorite website. The files will be generated by default in the \bin folder of the solution. Just click the View button to launch them. Bear in mind that for the Web Archive and complete tabs, all the content from the target web page must be downloaded to the /bin folder, so it might take a little while! Although I don't provide any feedback events yet, I do emit a lot of progress feedback via the Debug.Write, so switch to the debug output tab to see what's happening in real time.

There are four tabs here, just like the four options IE provides in its Save As Type options. In MhtBuilder, these are the four methods being called, in the order they appear on the tabs:

Public Sub SavePageComplete(ByVal outputFilePath As String, Optional url As String)
Public Sub SavePageArchive(ByVal outputFilePath As String, Optional url As String)
Public Sub SavePage(ByVal outputFilePath As String, Optional url As String)
Public Sub SavePageText(ByVal outputFilePath As String, Optional url As String)

As of Windows XP Service Pack 2, HTML files opened from disk result in security blocks. In order to avoid this, we need to add the "Mark of the Web" to the file so IE knows what URL it came from, and can thus assign an appropriate security zone to the HTML. That's what the blnAddMark parameter is for; it causes the HTML file to be tagged with this single line at the top:

<!-- saved from url=(0027) -->

The other thing we need to do when saving these files is fix up the URLs. Any relative URLs such as:

<img src="/images/standard/logo225x72.gif">

must be converted to absolute URLs like so:

<img src="">

We do this using regular expressions, which gets us a NameValueCollection of all the references we need to fix. We loop through each reference and perform the fixup on the HTML string.

Private Function ExternalHtmlFiles() As Specialized.NameValueCollection
  If Not _ExternalFileCollection Is Nothing Then
    Return _ExternalFileCollection
  End If
  _ExternalFileCollection = New Specialized.NameValueCollection
  Dim r As Regex
  Dim html As String = Me.ToString
  Debug.WriteLine("Resolving all external HTML references from URL:")
  Debug.WriteLine("    " & Me.Url)
  '-- src='filename.ext' ; background="filename.ext"
  '-- note that we have to test 3 times to catch all quote styles: '', "", and none
  r = New Regex( _
    "(\ssrc|\sbackground)\s*=\s*((?<Key>'(?<Value>[^']+)')|" & _
    "(?<Key>""(?<Value>[^""]+)"")|(?<Key>(?<Value>[^ \n\r\f]+)))", _
    RegexOptions.IgnoreCase Or RegexOptions.Multiline)
    AddMatchesToCollection(html, r, _ExternalFileCollection)
  '-- @import "style.css" or @import url(style.css)
  r = New Regex( _
    "(@import\s|\S+-image:|background:)\s*?(url)*\s*?(?<Key>" & _
    "[""'(]{1,2}(?<Value>[^""')]+)[""')]{1,2})", _
    RegexOptions.IgnoreCase Or RegexOptions.Multiline)
    AddMatchesToCollection(html, r, _ExternalFileCollection)
  '-- <link rel=stylesheet href="style.css">
  r = New Regex( _
    "<link[^>]+?href\s*=\s*(?<Key>" & _
    "('|"")*(?<Value>[^'"">]+)('|"")*)", _
    RegexOptions.IgnoreCase Or RegexOptions.Multiline)
    AddMatchesToCollection(html, r, _ExternalFileCollection)
  '-- <iframe src="mypage.htm"> or <frame src="mypage.aspx">
  r = New Regex( _
    "<i*frame[^>]+?src\s*=\s*(?<Key>" & _
    "['""]{0,1}(?<Value>[^'""\\>]+)['""]{0,1})", _
    RegexOptions.IgnoreCase Or RegexOptions.Multiline)
    AddMatchesToCollection(html, r, _ExternalFileCollection)
  Return _ExternalFileCollection
End Function

We use a similar technique to get a list of all the files we need to download, which are then downloaded via my WebClientEx class. Why use that instead of the built in Net.WebClient? Good question! Because it doesn't support HTTP compression. My class, on the other hand, does:

Private Function Decompress(ByVal b() As Byte, _
      ByVal CompressionType As HttpContentEncoding) As Byte()

  Dim s As Stream
  Select Case CompressionType
    Case HttpContentEncoding.Deflate
      s = New Zip.Compression.Streams.InflaterInputStream(New MemoryStream(b), _
          New Zip.Compression.Inflater(True))
    Case HttpContentEncoding.Gzip
      s = New GZip.GZipInputStream(New MemoryStream(b))
    Case Else
      Return b
  End Select
  Dim ms As New MemoryStream
  Const chunkSize As Integer = 2048
  Dim sizeRead As Integer
  Dim unzipBytes(chunkSize) As Byte
  While True
    sizeRead = s.Read(unzipBytes, 0, chunkSize)
    If sizeRead > 0 Then
      ms.Write(unzipBytes, 0, sizeRead)
      Exit While
    End If
  End While
  Return ms.ToArray
End Function

HTTP compression is a no-brainer: it increases your effective bandwidth by 75 percent by using standard GZIP compression-- courtesy of the SharpZipLib library.


Creating MHTML files isn't hard, but there are lots of little gotchas when dealing with HTML, regular expressions, and HTTP downloads. I tried to document all the difficult bits in the source code. I've also tested MhtBuilder on dozens of different websites so far with excellent results.

There are many more details and comments in the source code provided at the top of the article, so check it out. Please don't hesitate to provide feedback, good or bad! I hope you enjoyed this article. If you did, you may also like my other articles as well.


  • Sunday, September 12, 2004 - Published.
  • Monday, March 28, 2005 - Version 2.0
    • Completely rewritten!
    • Autodetection of content encoding (e.g., international web pages), tested against multi-language websites.
    • Now correctly decompresses both types of HTTP compression.
    • Supports completely in-memory operation for server-side use, or on-disk storage for client use.
    • Now works on web pages with frames and IFrames, using recursive retrieval.
    • HTTP authentication and HTTP Proxy support.
    • Allows configuration of browser ID string to retrieve browser-specific content.
    • Basic cookie support (needs enhancement and testing).
    • Much improved regular expressions used for parsing HTTP.
    • Extensive use of VB.NET 2005 style XML comments throughout.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United States United States
My name is Jeff Atwood. I live in Berkeley, CA with my wife, two cats, and far more computers than I care to mention. My first computer was the Texas Instruments TI-99/4a. I've been a Microsoft Windows developer since 1992; primarily in VB. I am particularly interested in best practices and human factors in software development, as represented in my recommended developer reading list. I also have a coding and human factors related blog at

You may also be interested in...

Comments and Discussions

QuestionMaking it work with IE9 Pin
NichUK23-Jan-13 8:37
memberNichUK23-Jan-13 8:37 
AnswerRe: Making it work with IE9 Pin
samsonfr24-Dec-14 4:51
membersamsonfr24-Dec-14 4:51 
QuestionCan we mention this in the credits under CPOL license? Pin
albert.dc6-Feb-12 23:31
memberalbert.dc6-Feb-12 23:31 
Question[FIX] Certain background URLs are wrong Pin
albert.dc30-Sep-11 10:07
memberalbert.dc30-Sep-11 10:07 
QuestionUsage Restrictions? Pin
marchesb17-Aug-11 6:45
membermarchesb17-Aug-11 6:45 
GeneralMy vote of 5 Pin
Bob@work27-Jul-11 7:31
memberBob@work27-Jul-11 7:31 
QuestionAlt to MHT builder-- no dotNET required Pin
Member 807420011-Jul-11 1:21
memberMember 807420011-Jul-11 1:21 
Aram Azhari5-Nov-11 21:08
memberAram Azhari5-Nov-11 21:08 
Generalembedding flash file in mht Pin
aj862210-Jun-11 3:12
memberaj862210-Jun-11 3:12 
GeneralMy vote of 5 Pin
johnson_han28-Jul-10 20:38
memberjohnson_han28-Jul-10 20:38 
GeneralProposed way to support file:///... based requests Pin
marchesb12-May-10 9:38
membermarchesb12-May-10 9:38 
QuestionHow to render this website ? Pin
Battosaiii25-Jan-10 6:41
memberBattosaiii25-Jan-10 6:41 
Questionrendering error using mht builder Pin
william saylor30-Dec-09 10:17
memberwilliam saylor30-Dec-09 10:17 
QuestionFile download in https Pin
Gargi K3-Apr-09 2:02
memberGargi K3-Apr-09 2:02 
QuestionRe: File download in https Pin
Greg Hauptmann6-Oct-09 10:58
memberGreg Hauptmann6-Oct-09 10:58 
QuestionRe: File download in https Pin
m.daveiga3-May-10 4:49
memberm.daveiga3-May-10 4:49 
GeneralGood article Pin
Donsw15-Mar-09 17:34
memberDonsw15-Mar-09 17:34 
GeneralIE Pin
BenAA2-Sep-08 7:20
memberBenAA2-Sep-08 7:20 
QuestionMS Word Open the mht error Pin
yanglz999-Jun-08 17:39
memberyanglz999-Jun-08 17:39 
AnswerRe: MS Word Open the mht error [modified] Pin
gg6731-May-10 18:37
membergg6731-May-10 18:37 
GeneralGoing the other way Pin
urbane.tiger23-May-08 16:37
memberurbane.tiger23-May-08 16:37 
QuestionAnyone providing this code as an extension for Firefox 2? Pin
alternety3-Jan-08 9:43
memberalternety3-Jan-08 9:43 
QuestionMSIE7.0, VS2005, Vista Home Premium Not Working Pin
JustALark6-Dec-07 8:17
memberJustALark6-Dec-07 8:17 
QuestionImages and CSS files are being referenced to the website and not being encoded in the single file Pin
Baladitya Ganty20-Jul-07 6:42
memberBaladitya Ganty20-Jul-07 6:42 
QuestionTrying to get html files on my hard drive to be converted... Pin
itskyb16-Jul-07 10:04
memberitskyb16-Jul-07 10:04 
GeneralInteresting problem Pin
p10005-Jul-07 7:48
memberp10005-Jul-07 7:48 
GeneralRe: Interesting problem Pin
gordon byers10-Jun-09 5:05
membergordon byers10-Jun-09 5:05 
QuestionHas anyone got this workng on vista / vs2005 / ie7 ? Pin
Mootah21-Jun-07 10:43
memberMootah21-Jun-07 10:43 
AnswerFixed it....well, to be honest, Kyle fixed it Pin
Mootah21-Jun-07 11:34
memberMootah21-Jun-07 11:34 
GeneralRe: Fixed it....well, to be honest, Kyle fixed it Pin
robalexclark5-Nov-08 7:00
memberrobalexclark5-Nov-08 7:00 
QuestionJava applets Pin
vitorg20-Jun-07 2:41
membervitorg20-Jun-07 2:41 
GeneralIIS6.0 Windows 2003 Pin
RajeshCR4-Jun-07 21:25
memberRajeshCR4-Jun-07 21:25 
QuestionHow to make it to Batch Process? Pin
Elven Wong28-Mar-07 23:32
memberElven Wong28-Mar-07 23:32 
GeneralAwesome! Just what I've been looking for. Pin
saab340b27-Mar-07 6:39
membersaab340b27-Mar-07 6:39 
Questionwhy the .Mht files are showing as text files? Pin
govindaraj.perumal15-Mar-07 21:46
membergovindaraj.perumal15-Mar-07 21:46 
AnswerRe: why the .Mht files are showing as text files? Pin
ChristianW8-Jan-08 0:01
memberChristianW8-Jan-08 0:01 
GeneralRe: why the .Mht files are showing as text files? Pin
ChristianW8-Jan-08 0:21
memberChristianW8-Jan-08 0:21 
GeneralDownload progress Pin
udvranto3-Feb-07 12:15
memberudvranto3-Feb-07 12:15 
QuestionTrouble saving long url (but not so long! Less than 260 characters, I mean) [modified] Pin
La raza22-Dec-06 6:07
memberLa raza22-Dec-06 6:07 
AnswerRe: Trouble saving long url (but not so long! Less than 260 characters, I mean) Pin
La raza28-Dec-06 6:00
memberLa raza28-Dec-06 6:00 
QuestionBrowser reads but this program doesn't , why ? Pin
dlwells10-Dec-06 15:55
memberdlwells10-Dec-06 15:55 
QuestionHow i can save the htm output from MS PowerPoint to mhtml format Pin
Mohammad Hammad28-Nov-06 9:42
memberMohammad Hammad28-Nov-06 9:42 
QuestionWebFile.Download() code question Pin
hev8-Nov-06 3:32
memberhev8-Nov-06 3:32 
Generalawesome Pin
Tim Kohler18-Aug-06 10:27
memberTim Kohler18-Aug-06 10:27 
QuestionProxy Server help [modified] Pin
Syed Javed22-Jul-06 14:35
memberSyed Javed22-Jul-06 14:35 
GeneralA contribution Pin
Yehuda A15-Jul-06 11:39
memberYehuda A15-Jul-06 11:39 
GeneralRe: A contribution Pin
hev8-Nov-06 7:15
memberhev8-Nov-06 7:15 
QuestionHow can I Convert MHTML to HTML Pin
xfary3-Jul-06 16:56
memberxfary3-Jul-06 16:56 
Questionhow can i do multiple html files at once Pin
cnrock27-Jun-06 18:07
membercnrock27-Jun-06 18:07 
GeneralIs this able to do multiple html files at once Pin
sdejager27-Jun-06 14:56
membersdejager27-Jun-06 14:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151125.3 | Last Updated 4 Apr 2005
Article Copyright 2004 by wumpus1
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid