views:

601

answers:

3

I am trying to utilize the AttachmentCollection Class in C# and when I try to create a new instance of it it gives me an error saying "Error 32 The type 'System.Net.Mail.AttachmentCollection' has no constructors defined".... Here is what I was trying, how to a create a new instance of this if there are no constructors defined ?

AttachmentCollection attachmentCollection = new AttachmentCollection();

Thanks for your help!

+1  A: 

You can't create a new instance of it without using reflection.

Instead, you can create a new MailMessage "message = new MailMessage(...)" (which creates it's own AttachmentCollection), and call "message.Attatchments.Add( ... )" to add an attachment.

The constructor for AttachmentCollection is internal, it's a type designed to only be used from MailMessage.

See the msdn docs for AttachmentCollection.

Philip Rieck
+2  A: 

I don't think you're using the AttachmentCollection correctly. Check out the example from the MSDN docs (basically, you should be using messages.Attachments.add(foo):

string file = "data.xls";
MailMessage message = new MailMessage(
   "[email protected]",
   "[email protected]",
   "Quarterly data report.",
   "See the attached spreadsheet.");

Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
brien
+2  A: 

Some types aren't designed to be instantiated.

They might be Abstract, meaning that you are expected to extend the class and fill in some of its functionality.

They might also require some extensive work to get them created correctly. Those types often expose public static methods or have factories which you can use to instantiate them.

The docs state that "Instances of the AttachmentCollection class are returned by the MailMessage.AlternateViews and MailMessage.Attachments properties." Seems like the designers didn't want you to create this collection; its purpose is to be used only with the MailMessage class.

Let the MailMessage class handle its AttachmentCollections for you. Create an instance of MailMessage and then fill in AlternateViews and Attachments, rather than create the collection, fill it in and then assign it to the properties.

One last thing, most public properties that are collections don't have setters. Its considered a bad design to allow users of your types to be able to set or even null out your public collection properties.

Will