Cannot convert from 'string[]' to 'System.Net.Mail.Attachment'

2.3k views Asked by At

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!

2

There are 2 answers

2
Paul Michaels On BEST ANSWER
Directory.GetFiles(file);

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

var attachment = new Attachment(filePath));
0
Derviş Kayımbaşıoğlu On

Try this

 Directory.GetFiles(file).ToList()
     .ForEach(t =>  x.Attachments.Add(new Attachment(t)));