使用memorystream

时间:2019-02-07 06:46:56

标签: c#

我正在控制器中创建一个ics文件。使用asp.net core 2.0 mvc。现在,我已经完成了内容和所有工作,可以将ics文件作为邮件附件发送。但是我不想在我的PC上本地创建文件,我想使用memorystream或没有物理路径的东西。

这是我创建ics内容的方式:


string schLocation = "Nord 1";
            string schSubject = "Badge-Austausch";
            string schDescription = "Termin zum Austauschen des Badges";
            System.DateTime schBeginDate = Convert.ToDateTime(DateOwnRegister);
            System.DateTime schEndDate = Convert.ToDateTime(schBeginDate.AddMinutes(30));
            string[] contents = { "BEGIN:VCALENDAR",
                               "PRODID:-//Flo Inc.//FloSoft//EN",
                               "BEGIN:VEVENT",
                               "DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
                               "DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
                               "LOCATION:" + schLocation,
                          "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription,
                               "SUMMARY:" + schSubject, "PRIORITY:3",
                          "END:VEVENT", "END:VCALENDAR" 

这就是我一直试图使用内存流的方式:

char[] charArray = contents.SelectMany(x => x.ToCharArray()).ToArray();
            byte[] byteArray = Encoding.UTF8.GetBytes(charArray);
            System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(charArray));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
            writer.Write(byteArray);

这就是我将其作为附件发送的方式。发送工作,但我无法在Outlook中打开文件。因此它不能用作日历邀请;

System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar");
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, contype);
                attach.ContentDisposition.FileName = "myFile.ics";
                msg.Attachments.Add(attach);
                sc.Send(msg);

对于我如何使它起作用的任何想法或解决方案感到高兴。正如我说的那样,当我从本地数据发送文件时,“内容”起作用了,但是没有本地路径的发送还没有起作用。

1 个答案:

答案 0 :(得分:0)

使用字符串生成器使其工作。

 StringBuilder sb = new StringBuilder();
            foreach (var line in contents)
            {
                sb.AppendLine(line);

            }
            var calendarBytes = Encoding.UTF8.GetBytes(sb.ToString());
            MemoryStream memorystream = new MemoryStream(calendarBytes);
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(memorystream, "event.ics", "text/calendar");```
相关问题