views:

475

answers:

3

I'm sending attachments using the System.Net.Mail.SmtpClient in C#.
The attachment names are the same as the name of the file I pass into the attachment constructor

myMail.Attachments.Add(new Attachment(attachmentFileName));

How would I go about setting a "nice" name for the attachment? The names I currently have are basically numeric IDs indicating which occurrence of a report is attached. My users are looking for something more friendly like "results.xls".

+1  A: 

Save the attachment to the temp folder with the desired name then attach it. Don't forget to delete it after you send the email so the temp folder doesn't grow too large.

Edit: The accepted answer is much better but I'll leave this here for others that go down the same thought path and see how wrong it is.

Paul Alexander
That just feels "dirty" <G>. It's what I originally proposed to a co worker, but their comment was "There's GOT to be a better way"
Brad Bruce
+5  A: 

See Attachment.Name Property:

Gets or sets the MIME content type name value in the content type associated with this attachment.

You can set the Attachment .Name property to anything you like. In the example inside the last link, you could have :

// Create  the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
data.Name = "VeryNiceName.dat"; //(not in original example)
...
message.Attachments.Add(data);
gimel
Beat me to it! ;-) +1
Cerebrus
The description SO doesn't reflect this. (Yes, if you turn your head sideways and squint you can read this into the description, but it doesn't jump out at you) THANKS
Brad Bruce
Always look for "Gets or sets" in properties.
gimel
Hey, much better than my answer. Guess that's been updated in 2.x.
Paul Alexander
A: 

You can use this constructor for Attachment

Partha Choudhury