当前位置: 动力学知识库 > 问答 > 编程问答 >

email - C# Add attachment to mailmessage without knowing the extension

问题描述:

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!

网友答案:

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));
}
网友答案:

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
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: