/// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="id"></param> /// <returns></returns> private static byte[] GetObject(byte[] bytes, string id) { using (var stream = new MemoryStream(bytes)) { var contents = new StreamContent(stream) { Headers = { ContentType = MediaTypeHeaderValue.Parse(GetBoundary(bytes).Insert(0, "multipart/related; ")) } }.ReadAsMultipartAsync(new MultipartRelatedStreamProvider()).Result.Contents; foreach (var type in contents.Select(t => t.Headers.ContentType).Where(t => t.CharSet != null)) { type.CharSet = type.CharSet.Replace("\"", ""); } HttpContent content; if (string.IsNullOrEmpty(id)) { content = contents.FirstOrDefault(t => !t.Headers.Contains("Content-ID")); } else { content = contents.FirstOrDefault(t => { IEnumerable <string> values; if (t.Headers.TryGetValues("Content-ID", out values)) { return(values.Contains(id)); } return(false); }); } if (content == null) { return(null); } bytes = content.ReadAsByteArrayAsync().Result; switch (content.Headers.GetValues("Content-Transfer-Encoding").FirstOrDefault()) { case "base64": { bytes = Convert.FromBase64String(Encoding.ASCII.GetString(bytes)); break; } case "quoted-printable": { var instance = typeof(TransferEncoding).Assembly.CreateInstance( "System.Net.Mime.QuotedPrintableStream", false, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { stream, true }, null, null); if (instance == null) { throw new FormatException("Quoted printable instance was not created."); } var methodInfo = instance.GetType().GetMethod("DecodeBytes"); if (methodInfo != null) { bytes.Resize((int)methodInfo.Invoke(instance, new object[] { bytes, 0, bytes.Length })); } break; } default: { throw new FormatException("Transfer encoding was unexpected."); } } var charset = content.Headers.ContentType.CharSet; if (string.IsNullOrEmpty(charset)) { return(bytes); } var encoding = Encoding.GetEncoding(charset); if (encoding.CodePage == Encoding.UTF8.CodePage) { return(bytes); } return(Encoding.Convert(encoding, Encoding.UTF8, bytes)); } }