C# Add attachment to mailmessage without knowing the extension

16,329

Solution 1

Assuming filename is a file name only and does not contain other path components:

foreach (string file in Directory.GetFiles(@"M:\", filename + ".*"))
{
   yourMailMessage.Attachments.Add(new System.Net.Mail.Attachment(file));
}

If filename does contain sub-directories then

string fullPath = Path.Combine(@"M:\", filename + ".*");
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath)))
{
   yourMailMessage.Attachments.Add(new System.Net.Mail.Attachment(file));
}

Solution 2

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
    }
}
Share:
16,329
user2520459
Author by

user2520459

Updated on June 04, 2022

Comments

  • user2520459
    user2520459 almost 2 years

    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!