I am working on a web project using MVC that requires me to select multiple values (cities) from a combobox and returning data that is pulled from SQL and a string is built from the data. Then, it's sent to a byte[] stream via a MemoryStream to be attached to an email The attachment is in ".csv" format. When I select, let's say, "3" cities and send it to my action, only the first attachment has data. The other two attachments are created, but the attachments are blank when I open up the email.
Below is a snippet of the code:
using (MailMessage message = new MailMessage())
using (SmtpClient client = new SmtpClient())
{
client.Host = "smtp.mymailserver.com";
client.Credentials = new System.Net.NetworkCredential("me@myemail.com", "mypass");
message.From = new MailAddress("maintenance@myemail.com");
message.To.Add(new MailAddress("justme@myemail.com"));
// split up the delimited locations into the list
List<String> listStrLineElements = LocationName.Split(',').ToList();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
foreach (var loc in listStrLineElements)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write(EmailAttachmentAdmin(loc, StartDate, EndDate), 0, EmailAttachmentAdmin(loc, StartDate, EndDate).Length); // this just gets my data as a concatenated string.
writer.Flush();
ms.Position = 0;
message.Attachments.Add(new Attachment(ms, loc.ToUpper() + "__" + StartDate.Month.ToString() + "-" + StartDate.Year.ToString() + "-TO-" + EndDate.Month.ToString() + "-" + EndDate.Year.ToString() + ".csv", "text/csv"));
}
message.Subject = "TEST NOTIFICATION: Monthly Maintenance Report Submitted for: " + LocationName;
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
client.Send(message);
}
"EmailAttachmentAdmin" is a string method that I call to build the data string. I checked the data in SQL and there is in fact data. Another test was to select just one city/location to see if the attachment comes in the email and it's successfully populated. Can someone jump in and tell me what i'm doing wrong? Thanks.
I solved my problem which seemed to have nothing to do with the MemoryStream or writer. My problem was that I needed to "trim()" the whitespace after the "," in my "split". So, when my code was looking for the location, it couldn't find it. For example, I needed to process data for location "El Paso" but if it was after the first occurrence in the split, then it would have been, " El Paso". My switch/case statement could not find that occurrence, so it processed the data as "blank".