2012-04-30 40 views
0

我创建一个CSV文件,并将其连接到像这样的电子邮件...c#如何将附件保存到文件夹? .NET2

using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv))) 
      { 
       try 
       { 
        to = "[email protected]"; 
        string from = "[email protected]"; 
        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文件保存到一个文件夹?谢谢

+0

刚刚编辑我的答案,祝你好运。 – Ademar

回答

1

在System.IO的File.WriteAllText方法可能是实现这一目标的最简单的方法:

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

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

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. 
+0

在这里流,我用csv? – Beginner

+0

对不起,我的坏。从我在这里的.net 4项目获得代码。也没有承诺你的第一个评论。让我检查如何处理.net 2. – Ademar

+0

看看这里。可能有帮助。 http://msdn.microsoft.com/en-us/library/system.io.memorystream(v=vs.80).aspx – Ademar

相关问题