2014-07-09 86 views
0

是否可以將字符串[]轉換爲字節[]?我試圖發送ICS文件,但我想避免將其保存在服務器上並將其恢復。這裏是我到目前爲止的代碼,並試圖轉換爲字節[]字符串數組到字節數組C#

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("[email protected]", "[email protected]"); 
      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
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. 
+1

只是作爲一個提示:我覺得ICS格式希望它是多線,因此在'的string.join分隔'使用'Environment.NewLine'。 –

+1

@PatrickHofman好點。 – CathalMF

3

我會創建一個string,因爲您的string[]沒有任何用途。您可以使用Encoding.UTF8.GetBytes來獲取該string的實際字節。

在此示例中,我使用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());