0

我正在创建一个 csv 文件并将其附加到这样的电子邮件中......

using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
            {
                try
                {
                    to = "email@email.com";
                    string from = "user@email.co.uk";
                    string subject = "Order p"+ OrderNumber;
                    string body = result;
                    SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
                    MailMessage mailObj = new MailMessage(from, to, subject, body);
                    Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
                    attachment.Name = "p" + OrderNo + "_" + CustomerReference+".csv";
                    mailObj.Attachments.Add(attachment);
                    SMTPServer.Send(mailObj);
                }
                catch (Exception ex)
                { }
            }

这工作正常,但我如何将相同的 csv 文件保存到文件夹中?谢谢

4

2 回答 2

1

System.IO 中的File.WriteAllText方法可能是完成此任务的最简单方法:

File.WriteAllText("<destination>", csv);

<destination>将 CSV 保存到的文件路径在哪里。如果该文件尚不存在,将创建该文件,否则将被覆盖。

于 2012-04-30T15:46:41.530 回答
0

您必须将流保存到一个位置:

var newfile = new StreamWriter(path_filename);

foreach (var l in stream)
   newfile.WriteLine(l);
newfile.Close();

编辑:

改用这个:

StreamWriter outputfile = new StreamWriter("c:\temp\outputfile.csv"); 

然后是 foreach 循环。

编辑 2(来自 msdn 站点):

   // Read the first 20 bytes from the stream.
   byteArray = new byte[memStream.Length];
   count = memStream.Read(byteArray, 0, 20);

   // Read the remaining bytes, byte by byte.
   while(count < memStream.Length)
            {
                byteArray[count++] = 
                    Convert.ToByte(memStream.ReadByte());
            }

   // Decode the byte array into a char array 
   // and write it to the console.
   charArray = new char[uniEncoding.GetCharCount(
   byteArray, 0, count)];
   uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray); //here you should send to the file as the first example i wrote instead of to writing to console.
于 2012-04-30T15:41:07.923 回答