字符串数组到字节数组c#

本文关键字:数组 到字节 字符串 | 更新日期: 2023-09-27 18:12:20

是否可以将字符串[]转换为字节[]?我试图发送ICS文件,但我想避免将其保存在服务器上并检索它回来。这是我到目前为止的代码,它在试图转换为字节[]

时中断了
string schLocation = "Conference Room";
            string schSubject = "Business visit discussion";
            string schDescription = "Schedule description";
            System.DateTime schBeginDate = Convert.ToDateTime("7/13/2014 10:00:00 PM");
            System.DateTime schEndDate = Convert.ToDateTime("7/13/2014 11:00:00 PM");
            //PUTTING THE MEETING DETAILS INTO AN ARRAY OF STRING
            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" };
            //byte[] data = contents.Select(x => Byte.Parse(x)).ToArray();
            byte[] data = contents.Select(x => Convert.ToByte(x, 16)).ToArray();
            MemoryStream ms = new MemoryStream(data);
            MailMessage message = new MailMessage("me@email.com", "you@email.com");
            message.Subject = schSubject;
            message.Body = "This is test";
            message.IsBodyHtml = false;
            message.Attachments.Add(new Attachment(ms, "meeting.ics"));
            SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]);
            client.Send(message);

我得到以下错误:其他不可解析字符位于字符串的末尾。

字符串数组到字节数组c#

我将创建一个单独的string,因为您的string[]没有任何用途。您可以使用Encoding.UTF8.GetBytesstring获取实际字节。

在这个示例中,出于性能原因,我使用StringBuilder:

StringBuilder sb = new StringBuilder();
sb.AppendLine("BEGIN:VCALENDAR");
sb.AppendLine("PRODID:-//Flo Inc.//FloSoft//EN");
sb.AppendLine("BEGIN:VEVENT");
sb.AppendLine("DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd''THHmmss''Z"));
sb.AppendLine("DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd''THHmmss''Z"));
sb.AppendLine("LOCATION:" + schLocation);
sb.AppendLine("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription);
sb.AppendLine("SUMMARY:" + schSubject, "PRIORITY:3");
sb.AppendLine("END:VEVENT", "END:VCALENDAR");
byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
string[] abc = new string[]{"hello", "myfriend"};
string fullstring = String.Join(Environment.NewLine, abc);    // Joins all elements in the array together into a single string.
byte[] arrayofbytes = Encoding.Default.GetBytes(fullstring);     // Convert the string to byte array.