-3

i successfully writed an auto add attachment to email if the condition FileInfo.Exists is true as this:

    if (filename.Exists)
    {
        message.Attachments.Add(new Attachment(path + @"\filefolder\filename.extension"));

    }

I have a series of this codes to attach many attachments in line; my question is how to give a name to every attachment? Something like:

    if (filename.Exists)
    {
        message.Attachments.Add(new Attachment(path + @"\filefolder\filename.extension"));
      //here i would like to write code to assign a different name for each attachment

    }
    if (filename2.Exists)
    {
        message.Attachments.Add(new Attachment(path + @"\filefolder2\filename2.extension"));
        //here i would like to write code to assign a different name for each attachment
    }

Since many of these attachments has the same name.extension i would like to know the relative name of the original attachment instad of having multiple files with the same names in my received email.

Thanks for your help.

CSharpie
  • 9,195
  • 4
  • 44
  • 71
Kranio23
  • 11
  • 3

1 Answers1

0

Modify your code to take advantage of the FileInfo object you've got already, then use Path.GetFileNameWithoutExtension() to extract the name.

var contentName = Path.GetFileNameWithoutExtension(filename); 
message.Attachments.Add(new Attachment(filename.FullName) { Name = contentName });

You can also simplify this further if you have the FileInfo objects in a collection. Assuming that files is an IEnumerable<FileInfo>, what about this?

var attachments = files
    .Where(f => f.Exists)
    .Select(f => new
    {
        Path = f.FullName,
        ContentName = Path.GetFileNameWithoutExtension(f.FullName)
    });

foreach (var attachmentInfo in attachments)
{
    message.Attachments.Add(
        new Attachment(attachmentInfo.Path) { Name = attachmentInfo.ContentName });
}

The first line is a set of LINQ operators that project the FileInfo enumerable to a anonymous type that has the extensionless name and full path ready to go. The loop enumerates those and uses the same method you're using as before to add the attachments.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • This could be nice but unfortunately i need to "assign a name of my preference" to each attachment since many of those attachments has the identical name but comes from different directories. So maybe another method which could fit my question is to retrieve the path of the attachment so i can know where the attachment (which can have the same name of another) comes from. – Kranio23 Feb 07 '16 at 15:32
  • Your question was to how to assign a name to each attachment. I believe this answers that question. You can use this sample code, and the point where it assigns `ContentName` to your liking. – jdphenix Feb 07 '16 at 15:35