C# Add attachment to mailmessage without knowing the extension

user2520459 picture user2520459 · Jun 26, 2013 · Viewed 16.2k times · Source

A system generates files with different extensions. Those files have to be sent to an email address.

How can I put a file in an attachment without knowing the extension

For example "sample.xls" has to be added to the attachments but the application can also add "sample.txt", how do I handle that? I now have

attachment = new System.Net.Mail.Attachment(@"M:/" + filename + ".xls");

I want something like this

attachment = new System.Net.Mail.Attachment(@"M:/" + filename); // this didnt work

So that it sends any type of files. By the way, the filename isn't coming from code, but from a database without any extensions, so plain "sample" and it has to send the file with unknown extension, and it has to send it with the correct extension at the end.

Help will be really appreciated!

Answer

r.mirzojonov picture r.mirzojonov · Jun 26, 2013

Maybe this can help you(if you want to perform it by looping):

string[] files = Directory.GetFiles("Directory of your file");
foreach (string s in files)
{
    if (s.Contains(@"FileName without extension"))
    {
        attachment = new System.Net.Mail.Attachment(s);
        mailMessage.Attachments.Add(attachment);   // mailMessage is the name of message you want to attach the attachment
    }
}