【问题标题】:c# how to save an attachment to a folder? .Net2c#如何将附件保存到文件夹? .Net2
【发布时间】:2012-04-30 15:36:46
【问题描述】:

我正在创建一个 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 文件保存到文件夹中呢?谢谢

【问题讨论】:

  • 刚刚编辑了我的答案,祝你好运。

标签: c# export-to-csv


【解决方案1】:

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

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

&lt;destination&gt; 是保存 CSV 文件的路径。如果该文件尚不存在,则创建该文件,否则将被覆盖。

【讨论】:

    【解决方案2】:

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

    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.
    

    【讨论】:

    • 这里的流,我用csv吗?
    • 对不起,我的错。从我这里的 .net 4 项目中获取代码。也没有理解你的第一条评论。让我看看如何处理 .net 2。
    • 看看这里。可能有帮助。 msdn.microsoft.com/en-us/library/…
    • erm 我认为这不是写入文件,我目前使用流来创建文件,只需要知道如何保存它
    • 所以你只需要像我输入的答案一样,创建一个流写入器并从你的内存流中写入它,而不是使用 var 单词。刚刚编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2012-08-31
    相关资源
    最近更新 更多