Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2008/.NET Framework 3.5

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
Attachment (Constructor) (Stream, String, String)

Actualización: noviembre 2007

Inicializa una nueva instancia de la clase Attachment con la cadena, el nombre y la información de tipo MIME que se hayan especificado.

Espacio de nombres:  System.Net.Mail
Ensamblado:  System (en System.dll)
Visual Basic (Declaración)
Public Sub New ( _
    contentStream As Stream, _
    name As String, _
    mediaType As String _
)
Visual Basic (Uso)
Dim contentStream As Stream
Dim name As String
Dim mediaType As String

Dim instance As New Attachment(contentStream, _
    name, mediaType)
C#
public Attachment(
    Stream contentStream,
    string name,
    string mediaType
)
Visual C++
public:
Attachment(
    Stream^ contentStream, 
    String^ name, 
    String^ mediaType
)
J#
public Attachment(
    Stream contentStream,
    String name,
    String mediaType
)
JScript
public function Attachment(
    contentStream : Stream, 
    name : String, 
    mediaType : String
)

Parámetros

contentStream
Tipo: System.IO..::.Stream
Objeto Stream legible que incluye el contenido de estos datos adjuntos.
name
Tipo: System..::.String
Objeto String que contiene el valor de la propiedad Name del objeto ContentType asociado a estos datos adjuntos. Este valor puede ser nullNothingnullptrreferencia null (Nothing en Visual Basic).
mediaType
Tipo: System..::.String
Objeto String que contiene la información Content-Header MIME de estos datos adjuntos. Este valor puede ser nullNothingnullptrreferencia null (Nothing en Visual Basic).
ExcepciónCondición
ArgumentNullException

El parámetro stream es nullNothingnullptrreferencia null (Nothing en Visual Basic).

FormatException

mediaType no tiene el formato correcto.

Si mediaType no es nullNothingnullptrreferencia null (Nothing en Visual Basic) ni es igual a String..::.Empty (""), se utilizará para crear la clase ContentType asociada a estos datos adjuntos.

Si tanto el parámetro mediaType como el parámetro name contienen información sobre Name, se utilizará el valor especificado en el parámetro name. La propiedad TransferEncoding está establecida en Base64.

Si el valor de la propiedad CanSeek de la secuencia es false, los datos adjuntos y el objeto MailMessage que los contiene no serán reutilizables. Deberá proporcionar una secuencia en la que se puedan realizar búsquedas para poder reutilizar los datos adjuntos.

En el siguiente ejemplo de código se muestra la forma de llamar a este constructor.

C#
        // The following example sends a summary of a log file as the message
        // and the log as an e-mail attachment.
        public static void SendNamedAndTypedErrorLog(string server, string recipientList)
        {
            // Create a message from logMailer@contoso.com to recipientList.
            MailMessage message = new MailMessage(
               "logMailer@contoso.com", recipientList);

            message.Subject = "Error Log report";
            string fileName = "log.txt";
            // Get the file stream for the error log.
            // Requires the System.IO namespace.
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader s = new StreamReader(fs);
            int errors = 0;
            while (s.ReadLine() != null)
            {
                // Process each line from the log file here.
                errors++;
            }
            // The e-mail message summarizes the data found in the log.
            message.Body = String.Format("{0} errors in log as of {1}",
                errors, DateTime.Now);
            // Close the stream reader. This also closes the file.
            s.Close();
            // Re-open the file at the beginning to make the attachment.
            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            // Create a name for the log data file.
            string name = "log" + DateTime.Now.ToString() + ".txt";
            // Create the attachment, name it, and specify the MIME type.
            Attachment data = new Attachment(fs, name, MediaTypeNames.Text.Plain);
            // Add the attachment to the message.
            message.Attachments.Add(data);
            // Send the message.
            // Include credentials if the server requires them.
            SmtpClient client = new SmtpClient(server);
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            client.Send(message);
            data.Dispose();
            // Close the log file.
            fs.Close();
        }
Visual C++
// The following example sends a summary of a log file as the message
// and the log as an e-mail attachment.
static void SendNamedAndTypedErrorLog( String^ server, String^ recipientList )
{

   // Create a message from logMailer@contoso.com to recipientList.
   MailMessage^ message = gcnew MailMessage( L"logMailer@contoso.com",recipientList );
   message->Subject = L"Error Log report";
   String^ fileName = L"log.txt";

   // Get the file stream for the error log.
   // Requires the System.IO namespace.
   FileStream^ fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   StreamReader^ s = gcnew StreamReader( fs );
   int errors = 0;
   while ( s->ReadLine() != nullptr )
   {

      // Process each line from the log file here.
      errors++;
   }

   message->Body = String::Format( L"{0} errors in log as of {1}", errors, DateTime::Now );

   // Close the stream reader. This also closes the file.
   s->Close();

   // Re-open the file at the beginning to make the attachment.
   fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );

   // Create a name for the log data file.
   String^ name = String::Format( L"log{0}.txt", DateTime::Now );

   // Create the attachment, name it, and specify the MIME type.
   Attachment^ data = gcnew Attachment( fs,name,MediaTypeNames::Text::Plain );

   // Add the attachment to the message.
   message->Attachments->Add( data );

   // Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();

   // Close the log file.
   fs->Close();
}


J#
// The following example sends a summary of a log file as the message
// and the log as an e-mail attachment.
public static void SendNamedAndTypedErrorLog(String server, 
    String recipientList)
{
    // Create a message from logMailer@contoso.com to recipientList.
    MailMessage message = new MailMessage("logMailer@contoso.com", 
        recipientList);

    message.set_Subject("Error Log report");
    String fileName = "log.txt";
    // Get the file stream for the error log.
    // Requires the System.IO namespace.
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    StreamReader s = new StreamReader(fs);
    int errors = 0;
    while (s.ReadLine() != null) {
        // Process each line from the log file here.
        errors++;
    }
    // The e-mail message summarizes the data found in the log.
    message.set_Body(String.Format("{0} errors in log as of {1}", 
        (Int32)errors, DateTime.get_Now()));
    // Close the stream reader. This also closes the file.
    s.Close();
    // Re-open the file at the beginning to make the attachment.
    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    // Create a name for the log data file.
    String name = "log" + DateTime.get_Now().ToString() + ".txt";
    // Create the attachment, name it, and specify the MIME type.
    Attachment data = new Attachment(fs, name, MediaTypeNames.Text.Plain);
    // Add the attachment to the message.
    message.get_Attachments().Add(data);
    // Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.set_Credentials(CredentialCache.get_DefaultNetworkCredentials());
    client.Send(message);
    data.Dispose();
    // Close the log file.
    fs.Close();
} //SendNamedAndTypedErrorLog

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker