Domanda

_data è un byte [] array di dati allegati.

Quando sto facendo questo:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));

Allegato viene vuoto. In realtà spettacoli prospettiva la dimensione del file, ma non è corretto.

Bene, ho pensato che c'è un problema nella mia _data. Poi ho deciso di provare questo approccio:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 fs = new FileStream(@"c:\Temp\"+attachment.Name,FileMode.CreateNew);
 fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
 fs.Flush();
 fs.Close();
 mailMessage.Attachments.Add(new Attachment(@"c:\Temp\" + attachment.Name));

E che le opere. Cosa c'è di sbagliato con il primo?

È stato utile?

Soluzione

Con la prima forma, non sei "riavvolgere" il flusso:

ms.Position = 0;

Così si è cercato di leggere dalla end del torrente, dove non c'era alcun dato.

Un modo più semplice di creare il MemoryStream è usare solo il costruttore però:

var ms = new MemoryStream(_data);
mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));

Altri suggerimenti

Non utilizzare GetBuffer. Utilizzare ms.ToArray().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top