1

I'm trying to add an attachment to an email I'm sending through my program but I'm getting the error referenced above.
I'm saving images taken during run time, and adding the name to a List which is called ImageFilenames. I'm then using the following code to retrieve the files and add them as an attachment, but I can't seem to figure out what I need to do to get this working.

            SaveScreenshots();

            using (MemoryStream stream = new MemoryStream())
            {
                using (SmtpClient SmtpServer = new SmtpClient())
                {
                    using (MailMessage mail = new MailMessage())
                    {
                        mail.From = new MailAddress("*****.******@******.com");
                        mail.To.Add("******@*****.com");
                        mail.Subject = this.Summary;
                        mail.Body = this.ToString();

                        SmtpServer.Port = ***;

                        foreach (string file in ImageFilenames)
                        {
                            var images = Directory.GetFiles(file);

                            mail.Attachments.Add(images); 

 //I tried this and the below method with no success

                            mail.Attachments.Add(Directory.GetFiles(file));
                        }

                        SmtpServer.Credentials = new System.Net.NetworkCredential("******@****.com", "********");
                        SmtpServer.EnableSsl = false;
                        SmtpServer.Host = "*****-1";

                        SmtpServer.Send(mail);
                    }
                }
            }
        }
        ClearScreenCaptures();

    }

Any help would be appreciated. Thank you!

Edit: Thank you for the suggested related question, but I am aware of how to add an attachment. My question was specifically how to do this using a list of filenames. Thank you though!

emmademontford
  • 122
  • 1
  • 11
  • 1
    You have the answer already. You cannot add a string to a collection of Attachments, you need to create attachments for each file that you return from getFiles() – ChrisBint Jan 21 '19 at 12:05

2 Answers2

1
Directory.GetFiles(file);

Returns a string array, you'll need to create an Attachment object. Something like this:

var attachment = new Attachment(filePath));
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
0

Try this

 Directory.GetFiles(file).ToList()
     .ForEach(t =>  x.Attachments.Add(new Attachment(t)));
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72