Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
AttachmentCollection Class

Stores attachments to be sent as part of an e-mail message.

System..::.Object
  System.Collections.ObjectModel..::.Collection<(Of <(Attachment>)>)
    System.Net.Mail..::.AttachmentCollection

Namespace:  System.Net.Mail
Assembly:  System (in System.dll)
Visual Basic
Public NotInheritable Class AttachmentCollection _
    Inherits Collection(Of Attachment) _
    Implements IDisposable
C#
public sealed class AttachmentCollection : Collection<Attachment>, 
    IDisposable
Visual C++
public ref class AttachmentCollection sealed : public Collection<Attachment^>, 
    IDisposable
F#
[<Sealed>]
type AttachmentCollection =  
    class
        inherit Collection<Attachment>
        interface IDisposable
    end

The AttachmentCollection type exposes the following members.

  NameDescription
Public propertyCountGets the number of elements actually contained in the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public propertyItemGets or sets the element at the specified index. (Inherited from Collection<(Of <(T>)>).)
Protected propertyItemsGets a IList<(Of <(T>)>) wrapper around the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Top
  NameDescription
Public methodAddAdds an object to the end of the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodClearRemoves all elements from the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Protected methodClearItemsRemoves all elements from the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodContainsDetermines whether an element is in the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodCopyToCopies the entire Collection<(Of <(T>)>) to a compatible one-dimensional Array, starting at the specified index of the target array. (Inherited from Collection<(Of <(T>)>).)
Public methodDisposeReleases all resources used by the AttachmentCollection.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetEnumeratorReturns an enumerator that iterates through the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIndexOfSearches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodInsertInserts an element into the Collection<(Of <(T>)>) at the specified index. (Inherited from Collection<(Of <(T>)>).)
Protected methodInsertItemInserts an element into the Collection<(Of <(T>)>) at the specified index. (Inherited from Collection<(Of <(T>)>).)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodRemoveRemoves the first occurrence of a specific object from the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Public methodRemoveAtRemoves the element at the specified index of the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Protected methodRemoveItemRemoves the element at the specified index of the Collection<(Of <(T>)>). (Inherited from Collection<(Of <(T>)>).)
Protected methodSetItemReplaces the element at the specified index. (Inherited from Collection<(Of <(T>)>).)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Explicit interface implemetationPrivate methodICollection..::.CopyToCopies the elements of the ICollection to an Array, starting at a particular Array index. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyICollection<(Of <(T>)>)..::.IsReadOnlyGets a value indicating whether the ICollection<(Of <(T>)>) is read-only. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyICollection..::.IsSynchronizedGets a value indicating whether access to the ICollection is synchronized (thread safe). (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyICollection..::.SyncRootGets an object that can be used to synchronize access to the ICollection. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIEnumerable..::.GetEnumeratorReturns an enumerator that iterates through a collection. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIList..::.AddAdds an item to the IList. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIList..::.ContainsDetermines whether the IList contains a specific value. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIList..::.IndexOfDetermines the index of a specific item in the IList. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIList..::.InsertInserts an item into the IList at the specified index. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyIList..::.IsFixedSizeGets a value indicating whether the IList has a fixed size. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyIList..::.IsReadOnlyGets a value indicating whether the IList is read-only. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate propertyIList..::.ItemGets or sets the element at the specified index. (Inherited from Collection<(Of <(T>)>).)
Explicit interface implemetationPrivate methodIList..::.RemoveRemoves the first occurrence of a specific object from the IList. (Inherited from Collection<(Of <(T>)>).)
Top

Instances of the AttachmentCollection class are returned by the MailMessage..::.AlternateViews and MailMessage..::.Attachments properties.

Use the AlternateViews property to specify copies of an e-mail message in different formats. For example, if you send a message in HTML, you might also want provide a plain text version in case some of the recipients use e-mail readers that cannot display HTML content.

Use the collection returned by the Attachments property to add an attachment, such as a file or the contents of a Stream to this MailMessage.

The following code example demonstrates how to create and send an e-mail message with an attachment.

C#
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            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);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                    ex.ToString() );              
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }
Visual C++
   static void CreateMessageWithAttachment( String^ server )
   {

      // Specify the file to be attached and sent.
      // This example assumes that a file named Data.xls exists in the
      // current working directory.
      String^ file = L"data.xls";

      // Create a message and set up the recipients.
      MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );

      // Create  the file attachment for this e-mail message.
      Attachment^ data = gcnew 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 );

      //Send the message.
      SmtpClient^ client = gcnew SmtpClient( server );

      // Add credentials if the SMTP server requires them.
      client->Credentials = CredentialCache::DefaultNetworkCredentials;
      client->Send( message );

      // Display the values in the ContentDisposition for the attachment.
      ContentDisposition^ cd = data->ContentDisposition;
      Console::WriteLine( L"Content disposition" );
      Console::WriteLine( cd );
      Console::WriteLine( L"File {0}", cd->FileName );
      Console::WriteLine( L"Size {0}", cd->Size );
      Console::WriteLine( L"Creation {0}", cd->CreationDate );
      Console::WriteLine( L"Modification {0}", cd->ModificationDate );
      Console::WriteLine( L"Read {0}", cd->ReadDate );
      Console::WriteLine( L"Inline {0}", cd->Inline );
      Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
      IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
         Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
      }

      data->~Attachment();
      client->~SmtpClient();
   }


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Biblioteca de clases de .NET Framework
AttachmentCollection (Clase)

Almacena datos adjuntos para que se envíen como parte de un mensaje de correo electrónico.

System..::.Object
  System.Collections.ObjectModel..::.Collection<(Of <(Attachment>)>)
    System.Net.Mail..::.AttachmentCollection

Espacio de nombres:  System.Net.Mail
Ensamblado:  System (en System.dll)
Visual Basic
Public NotInheritable Class AttachmentCollection _
    Inherits Collection(Of Attachment) _
    Implements IDisposable
C#
public sealed class AttachmentCollection : Collection<Attachment>, 
    IDisposable
Visual C++
public ref class AttachmentCollection sealed : public Collection<Attachment^>, 
    IDisposable
F#
[<Sealed>]
type AttachmentCollection =  
    class
        inherit Collection<Attachment>
        interface IDisposable
    end

El tipo AttachmentCollection expone los siguientes miembros.

  NombreDescripción
Propiedad públicaCountObtiene el número de elementos contenido realmente en Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Propiedad públicaItemObtiene o establece el elemento que se encuentra en el índice especificado. (Se hereda de Collection<(Of <(T>)>)).
Propiedad protegidaItemsObtiene un contenedor de IList<(Of <(T>)>) para la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Arriba
  NombreDescripción
Método públicoAddAgrega un objeto al final de la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoClearQuita todos los elementos de Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método protegidoClearItemsQuita todos los elementos de Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoContainsDetermina si un elemento se encuentra en la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoCopyToCopia la totalidad de Collection<(Of <(T>)>) en una matriz Array unidimensional y compatible, comenzando en el índice especificado de la matriz de destino. (Se hereda de Collection<(Of <(T>)>)).
Método públicoDisposeLibera todos los recursos utilizados por el objeto AttachmentCollection.
Método públicoEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object).
Método públicoGetEnumeratorDevuelve un enumerador que recorre en iteración la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método públicoIndexOfBusca el objeto especificado y devuelve el índice de base cero de la primera aparición en toda la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoInsertInserta un elemento en el índice especificado de la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método protegidoInsertItemInserta un elemento en el índice especificado de la colección Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método protegidoMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoRemoveQuita la primera aparición de un objeto específico de la interfaz Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método públicoRemoveAtQuita el elemento en el índice especificado de Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método protegidoRemoveItemQuita el elemento en el índice especificado de Collection<(Of <(T>)>). (Se hereda de Collection<(Of <(T>)>)).
Método protegidoSetItemReemplaza el elemento del índice especificado. (Se hereda de Collection<(Of <(T>)>)).
Método públicoToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoICollection..::.CopyToCopia los elementos de la interfaz ICollection a un objeto Array, a partir de un índice determinado de la clase Array. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaICollection<(Of <(T>)>)..::.IsReadOnlyObtiene un valor que indica si ICollection<(Of <(T>)>) es de solo lectura. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaICollection..::.IsSynchronizedObtiene un valor que indica si el acceso a ICollection está sincronizado (es seguro para la ejecución de subprocesos). (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaICollection..::.SyncRootObtiene un objeto que se puede utilizar para sincronizar el acceso a ICollection. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIEnumerable..::.GetEnumeratorDevuelve un enumerador que recorre en iteración una colección. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIList..::.AddAgrega un elemento a la interfaz IList. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIList..::.ContainsDetermina si la interfaz IList contiene un valor específico. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIList..::.IndexOfDetermina el índice de un elemento específico en la interfaz IList. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIList..::.InsertInserta un elemento en la interfaz IList, en el índice especificado. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaIList..::.IsFixedSizeObtiene un valor que indica si IList tiene un tamaño fijo. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaIList..::.IsReadOnlyObtiene un valor que indica si IList es de sólo lectura. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesPropiedad privadaIList..::.ItemObtiene o establece el elemento que se encuentra en el índice especificado. (Se hereda de Collection<(Of <(T>)>)).
Implementación explícita de interfacesMétodo privadoIList..::.RemoveQuita la primera aparición de un objeto específico de la interfaz IList. (Se hereda de Collection<(Of <(T>)>)).
Arriba

Las propiedades MailMessage..::.AlternateViews y MailMessage..::.Attachments devuelven instancias de la clase AttachmentCollection.

Utilice la propiedad AlternateViews para especificar distintos formatos para las copias de un mensaje de correo electrónico. Por ejemplo, si envía un mensaje en HTML y algunos de los destinatarios utilizan lectores de correo que no pueden mostrar contenido HTML, es probable que también desee proporcionar una versión de texto sin formato.

Utilice la colección devuelta por la propiedad Attachments para agregar datos adjuntos (como un archivo o el contenido de un objeto Stream) a este objeto MailMessage.

En el siguiente ejemplo de código se muestra la forma de crear y enviar un mensaje de correo electrónico con datos adjuntos.

C#
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            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);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                    ex.ToString() );              
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }
Visual C++
   static void CreateMessageWithAttachment( String^ server )
   {

      // Specify the file to be attached and sent.
      // This example assumes that a file named Data.xls exists in the
      // current working directory.
      String^ file = L"data.xls";

      // Create a message and set up the recipients.
      MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );

      // Create  the file attachment for this e-mail message.
      Attachment^ data = gcnew 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 );

      //Send the message.
      SmtpClient^ client = gcnew SmtpClient( server );

      // Add credentials if the SMTP server requires them.
      client->Credentials = CredentialCache::DefaultNetworkCredentials;
      client->Send( message );

      // Display the values in the ContentDisposition for the attachment.
      ContentDisposition^ cd = data->ContentDisposition;
      Console::WriteLine( L"Content disposition" );
      Console::WriteLine( cd );
      Console::WriteLine( L"File {0}", cd->FileName );
      Console::WriteLine( L"Size {0}", cd->Size );
      Console::WriteLine( L"Creation {0}", cd->CreationDate );
      Console::WriteLine( L"Modification {0}", cd->ModificationDate );
      Console::WriteLine( L"Read {0}", cd->ReadDate );
      Console::WriteLine( L"Inline {0}", cd->Inline );
      Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
      IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
         Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
      }

      data->~Attachment();
      client->~SmtpClient();
   }


.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker