[英]C# EWS Api on Exchange 2013 : Get an attachment into a Stream
我想從郵件中將附件文件轉換為流類型。 但是如何創建流? 我正確地獲取郵件項目(內容,主題,附件)。 請參閱以下鏈接: EWS托管API:獲取附件我嘗試執行以下操作:
int nbAttachments = message.Attachments.Count;
FileAttachment[] attachedFiles = new FileAttachment[nbAttachments];
for (int i=0; i < nbAttachments; i++)
{
attachedFiles[i] = message.Attachments[i] as FileAttachment;
}
for (int i = 0; i < attachments.Length; i++)
{
if (attachments[i].Name != null)
{
AttachmentCreationInformation infoAttachment = new AttachmentCreationInformation();
attachments[i].Load(infoAttachment.ContentStream);
infoAttachment.FileName = attachments[i].Name;
newItem.AttachmentFiles.Add(infoAttachment);
}
}
好吧,不要擔心我做了很多測試和管理異常但是把所有代碼都放在這里並不重要。
我發現這篇文章: MSDN論壇並嘗試以下方法:
FileStream stream = new FileStream(attachments [i] .Name,FileMode.Open);
byte [] byteArray = new byte [stream.Length];
stream.Read(byteArray,0,Convert.ToInt32(stream.Length));
stream.Close();
(這里我的文字被打破了,因為我無法將其轉換為代碼格式,所以對於斜體來說很抱歉......今天運氣不好)
但它搜索本地驅動器上的附件......
基本上我無法得到如何將我的附件[i]添加到FileStream var ...
非常感謝,真的。
如果我理解正確你想在某個地方保存附件? EWS為FileAttachment對象的Content屬性中存儲的每個文件提供了一個字節數組,從那里它非常容易:
foreach (var a in mail.Attachments)
{
FileAttachment fa = a as FileAttachment;
if(fa != null)
{
try
{
//if you don't call this the Content property may be null,
//depending on your property loading policy with EWS
fa.Load();
}
catch
{
continue;
}
using(FileStream fs = System.IO.File.OpenWrite("path_to_file"))
{
fs.Write(fa.Content, 0, fa.Content.Length);
}
}
}
如果你只是想讓一個Stream對象用它來做其他事情,那就創建一個MemoryStream:
MemoryStream ms = new MemoryStream(fa.Content);
感謝@anusiak :),
這是關於流的代碼:
for (int i = 0; i < attachments.Length; i++)
{
if (attachments[i].Name != null && attachments[i].Content != null)
{
MemoryStream mstream = new MemoryStream(attachments[i].Content);
AttachmentCreationInformation spAttachment = new AttachmentCreationInformation();
spAttachment.ContentStream = mstream;
spAttachment.FileName = attachments[i].Name;
newItem.AttachmentFiles.Add(spAttachment);
}
}
newItem.Update();
我必須為從郵件中提取的每個附件調用Load()方法,然后才能將它們存儲到FileAttachment var中。 然后我使用MemoryStream將數據流添加到我需要使用的特殊類型中。 其余代碼是將其添加到SharePoint列表中的項目,因此無需解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.