2012-04-30 63 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

相關問題