我想出了如何做到这一点,它并没有看起来那么困难。
在您的 web 服务命名空间中创建以下内容:
`
[Serializable]
public class MyAttachment
{
[DataMember]
public string Name { get; set; }
[DataMember]
public byte[] Bytes { get; set; }
}`
然后将以下内容添加到您的网络方法参数中:
MyAttachment[] attachment
在您的网络方法的执行块中添加以下内容:`
foreach (var item in attachment)
{
Stream attachmentStream = new MemoryStream(item.Bytes);
Attachment at = new Attachment(attachmentStream, item.Name);
msg.Attachments.Add(at);
}`
在您的客户端创建以下属性(或类似属性):
`
private ObservableCollection<ServiceProxy.MyAttachment> _attachmentCollection;
public ObservableCollection<ServiceProxy.MyAttachment> AttachmentCollection
{
get { return _attachmentCollection; }
set { _attachmentCollection = value; NotifyOfPropertyChange(() => AttachmentCollection); }
}`
在构造函数中新建公共属性 (AttachmentCollection)。
在 OpenFileDialog 应该返回文件的地方添加以下内容:`
如果 (openFileDialog.File != null)
{
foreach (FileInfo fi in openFileDialog.Files)
{
var tempItem = new ServiceProxy.MyAttachment();
tempItem.Name = fi.Name;
var source = fi.OpenRead();
byte[] byteArray = new byte[source.Length];
fi.OpenRead().Read(byteArray, 0, (int)source.Length);
tempItem.Bytes = byteArray;
source.Close();
AttachmentCollection.Add(tempItem);
}
}`
最后,在您调用网络方法发送电子邮件的地方,添加以下内容(或类似内容):
MailSvr.SendMailAsync(FromAddress, ToAddress, Subject, MessageBody, AttachmentCollection);
这对我有用,附件随邮件一起发送,其所有数据与原始文件完全相同。