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

时间:2014-07-09 13:54:00

标签: c# arrays asp.net-mvc bytearray

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

时中断
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);

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

2 个答案:

答案 0 :(得分:3)

我会创建一个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());

答案 1 :(得分:2)

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.