C# html转mht

时间:2022-02-26 03:13:03

项目中引入cdosys.dll组件,位置:  C:\Windows\System32\cdosys.dll

CDO、ADODB 这些类都来自于cdosys.dll组件

/// <summary>
/// 把Html格式二进制流转换成Mht格式的二进制流
/// </summary>
/// <param>Html格式的二进制流</param>
/// <returns>Mht格式的二进制流</returns>
public static byte[] ConvertHtmlUrlToMht(string htmlUrl)
{
string _CharSet = "gb2312";
string strMhtContent = string.Empty;
byte[] BytMhtContent = null;
CDO.Message message = new CDO.MessageClass();
ADODB.Stream stream = null;
message.MimeFormatted = true;
message.CreateMHTMLBody(htmlUrl, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
stream = message.GetStream();
stream.Charset = _CharSet;
strMhtContent = stream.ReadText(stream.Size);
BytMhtContent = Encoding.GetEncoding(_CharSet).GetBytes(strMhtContent);
return BytMhtContent;
}
/// <summary>
/// 把Html格式二进制流转换成Mht格式的二进制流,成功返回true,失败返回false
/// </summary>
/// <param>Html格式的二进制流</param>
/// <param>Mht文件的保存路径</param>
/// <returns>操作结果 成功:true,失败;false</returns>
public static bool ConvertHtmlUrlToMht(string htmlUrl, string filePath)
{
bool isConvertHtmlBytesToMht = false;
CDO.Message message = new CDO.MessageClass();
ADODB.Stream stream = null;
message.MimeFormatted = true;
message.CreateMHTMLBody(htmlUrl, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
stream = message.GetStream();
stream.SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
message = null;
stream.Close();
isConvertHtmlBytesToMht = true;
return isConvertHtmlBytesToMht;
}