The Hoju Saram

Wednesday, January 10, 2007

Http Upload and send Attachments in .Net

A while ago as part of a .net based web mail client I wrote some code to upload and then send files. This was in .Net 1.0 and there was no way to do this in-memory on the server. You had to do a temporary store->attach->send->delete.

This is was due to the fact that the Attachment class only worked with a file on disk. In 2.0 this has been updated so you can use an inputStream. So now attaching the uploaded files from a web page to a System.Net.Mail.MailMessage is as easy as:

public void AddUploadFilestoMessage(MailMessage msMessage)

System.Web.HttpFileCollection httpfiles = System.Web.HttpContext.Current.Request.Files;
Attachment mailAttachment;

if (httpfiles.Count != 0)
for (int iFile = 0; iFile < httpfiles.Count; iFile++)
System.Web.HttpPostedFile postedFile = httpfiles[iFile];

if (!(postedFile.FileName == ""))

String[] FileNameArr = postedFile.FileName.Split(@"\".ToCharArray());

mailAttachment = new Attachment(postedFile.InputStream, FileNameArr[FileNameArr.GetUpperBound(0)], postedFile.ContentType);





Post a Comment

Links to this post:

Create a Link

<< Home