亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

c#基礎知識之獲取exchange中的圖片

標簽:
C#

摘要

在exchange 2007或者2010中获取的邮件内容为html标签格式,也就是一个页面。如果里面含有img标签,你会发现img标签的src属性为cid:xxxxxxxxxxxx的一串字符串,并不是url,这时候就造成页面上图片显示不出来。

解决办法

在网上找了一种解决办法。

原文地址:http://stackoverflow.com/questions/6650842/ews-exchange-2007-retrieve-inline-images

首先创建cid的索引


private const string CidPattern = "cid:";

private static HashSet<int> BuildCidIndex(string html)
{
   var index = new HashSet<int>();
   var pos = html.IndexOf(CidPattern, 0);
   while (pos > 0)
   {
       var start = pos + CidPattern.Length;
       index.Add(start);
       pos = html.IndexOf(CidPattern, start);
   }
   return index;
}


在索引的基础上封装一个替换的方法


private static void AdjustIndex(HashSet<int> index, int oldPos, int byHowMuch)
{
   var oldIndex = new List<int>(index);
   index.Clear();
   foreach (var pos in oldIndex)
   {
       if (pos < oldPos)
           index.Add(pos);
       else
           index.Add(pos + byHowMuch);
   }          
}

private static bool ReplaceCid(HashSet<int> index, ref string html, string cid, string path)
{
   var posToRemove = -1;
   foreach (var pos in index)
   {
       if (pos + cid.Length < html.Length && html.Substring(pos, cid.Length) == cid)
       {
           var sb = new StringBuilder();
           sb.Append(html.Substring(0, pos-CidPattern.Length));
           sb.Append(path);
           sb.Append(html.Substring(pos + cid.Length));
           html = sb.ToString();

           posToRemove = pos;
           break;
       }
   }

   if (posToRemove < 0)
       return false;

   index.Remove(posToRemove);
   AdjustIndex(index, posToRemove, path.Length - (CidPattern.Length + cid.Length));

   return true;
}


在获取的item中获取附件


FileAttachment[] attachments = null;
var index = BuildCidIndex(sHTMLCOntent);
if (index.Count > 0 && item.Attachments.Count > 0)
{
   var basePath = Directory.GetCurrentDirectory();

   attachments = new FileAttachment[item.Attachments.Count];
   for (var i = 0; i < item.Attachments.Count; ++i)
   {
     var type = item.Attachments[i].ContentType.ToLower();
     if (!type.StartsWith("image/")) continue;                    
     type = type.Replace("image/", "");

     var attachment = (FileAttachment)item.Attachments[i];
     var cid = attachment.ContentId;
     var filename = cid + "." + type;
     var path = Path.Combine(basePath, filename);
     if(ReplaceCid(index, ref sHTMLCOntent, cid, path))
     {
        // only load images when they have been found          
        attachment.Load(path);
        attachments[i] = attachment;
     }
  }
}
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消