.net c# StreamWriter不写入文件

StreamWriter to do not write to file
2021-02-23
  •  译文(汉语)
  •  原文(英语)

我有一种将文件作为附件发送的方法.我使用StreamWriterMemoryStream创建附件.代码如下:

public void ComposeEmail(string from, string to, SmtpClient client)
    {
        MailMessage mm = new MailMessage(from, to, "Otrzymałeś nowe zamówienie od "+from , "Przesyłam nowe zamówienie na sprzęt");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        // Adding attachment:

        using (var ms = new System.IO.MemoryStream())
        {
            using (var writer = new System.IO.StreamWriter(ms))
            {
                writer.Write("Hello its my sample file");
                writer.Flush();

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                attach.ContentDisposition.FileName = "myFile.txt";

                mm.Attachments.Add(attach);
                try
                {
                    client.Send(mm);
                }
                catch (SmtpException e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }

如您在这些行中看到的,我将写入"文件":

writer.Write("Hello its my sample file");
writer.Flush();

在调试时,我可以看到它的MemoryStream长度为24(就像写入字符串的长度一样).但是邮箱中收到的文件为空.

我究竟做错了什么?

速聊1:
您是否尝试过在.Flush()之后关闭编写器?
速聊2:
您无需在StreamWriter,MemoryStream上使用Flush.
速聊3:
.s我无法在发送邮件之前关闭流.
速聊4:
FlushStreamWriter(相当)冗余的; 在某些情况下会添加数据
解决过程1

尝试倒带流:

writer.Flush();
ms.Position = 0; // <===== here

System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(
    System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);

否则,流仍将定位在最后,从那里读取将立即报告EOF.

速聊1:
冲洗是多余的
速聊2:
这很有趣,因为我正在查看的IL StreamWriter.Flush(),但实际上并非如此.当然可以.但是情况.
速聊3:
撇开:这里的经典比喻是"录像带"或"录音带";问题是,现在出现了新一代的开发人员,他们既没有看过也没有使用视频"磁带"或音频"磁带"; p
速聊4:
我还不年轻.我仍然记得用铅笔为c64的游戏音乐倒带:>
速聊5:
很好的解释.

I have a method in which I send File as attachment. I use StreamWriter and MemoryStream to create attachment. Code below:

public void ComposeEmail(string from, string to, SmtpClient client)
    {
        MailMessage mm = new MailMessage(from, to, "Otrzymałeś nowe zamówienie od "+from , "Przesyłam nowe zamówienie na sprzęt");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        // Adding attachment:

        using (var ms = new System.IO.MemoryStream())
        {
            using (var writer = new System.IO.StreamWriter(ms))
            {
                writer.Write("Hello its my sample file");
                writer.Flush();

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                attach.ContentDisposition.FileName = "myFile.txt";

                mm.Attachments.Add(attach);
                try
                {
                    client.Send(mm);
                }
                catch (SmtpException e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }

as You can see in these lines I write to "file":

writer.Write("Hello its my sample file");
writer.Flush();

While debugging I can see that MemoryStream has length of 24 ( just like length of string written to it). But file received in mailbox is empty.

What am I doing wrong?

Talk1:
have you tried closing the writer after the .Flush() ?
Talk2:
You don't need to use Flush on the StreamWriter,MemoryStream..Its redundant
Talk3:
.s I can not close stream before I send a mail.
Talk4:
the Flush on StreamWriter is not (quite) redundant; there are scenarios where it adds data
Solutions1

Try rewinding the stream:

writer.Flush();
ms.Position = 0; // <===== here

System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(
    System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);

Otherwise, the stream is still going to be positioned at the end, and reading from there will immediately report EOF.

Talk1:
Flush is redundant though
Talk2:
that's funny, because I'm looking at the IL of StreamWriter.Flush(), and it really isn't. Edge cases, sure. But cases.
Talk3:
aside: the classic analogy here is a "video tape" or "audio tape"; the problem is, a new generation of devs is now emerging that have neither seen nor used a video "tape" or an audio "tape" ;p
Talk4:
I'm not that young. I still remember rewinding tapes with music of with games for c64 with pencil :>
Talk5:
nice explaination.
转载于:https://stackoverflow.com/questions/23733049/streamwriter-to-do-not-write-to-file

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入