2012-04-30 14 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) 
       { } 
      } 

これはうまく動作しますが、どのようにiは、フォルダに同じCSVファイルを保存する?おかげ

+0

私の答えは、幸運を編集しました。 – Ademar

答えて

1

System.IOでFile.WriteAllText方法は、おそらくこれを実現する最も簡単な方法です:<destination>は、ファイルのパスです

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

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プロジェクトからのコードを得ました。また、あなたの最初のコメントを否定しませんでした。私はネットで行う方法をチェックさせてください。 – Ademar

+0

ここを見てください。役立つかもしれません。 http://msdn.microsoft.com/en-us/library/system.io.memorystream(v=vs.80).aspx – Ademar