I am trying to write a small console app using C#
on the top of .NET Core 2.2 framework.
The console app will make an HTTP-request to external API to get multiple images. I am able to make the request to the server and get the response. However, the server responds with a multipart response using MIMI messages.
I am able to parse the request and get the MIME-body for every message. But, I am unable to figure out how to create a file out of the content of the body.
Here is a sample of how the raw MIMI message begins with
I tried writing the body as a string to the file but it did not work
string body = GetMimeBody(message);
File.WriteAllText("image_from_string" + MimeTypeMap.GetExtension(contentType), bytes);
I also tried to convert the string to byte[]
like so but still did not work
byte[] bytes = Encoding.ASCII.GetBytes(body);
File.WriteAllBytes("image_from_ascii_bytes" + MimeTypeMap.GetExtension(contentType), bytes);
byte[] bytes = Encoding.Default.GetBytes(body);
File.WriteAllBytes("image_from_default_bytes" + MimeTypeMap.GetExtension(contentType), bytes);
byte[] bytes = Encoding.UTF8.GetBytes(body);
File.WriteAllBytes("image_from_utf8_bytes" + MimeTypeMap.GetExtension(contentType), bytes);
By "not working" I mean that the image does not open correctly. The photo viewer says "the image appears to be damaged or corrupted."
How can I correctly make a good image out of the message?
UPDATED
Here is the code along with the parsing parts
var responseContentType = response.Content.Headers.GetValues("Content-Type").FirstOrDefault();
string splitter = string.Format("--{0}", GetBoundary(responseContentType));
string content = await response.Content.ReadAsStringAsync();
var messages = content.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
foreach (var message in messages)
{
var mimiParts = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
if (mimiParts.Length == 0)
{
continue;
}
string contentId = Str.GetValue("Content-ID", mimiParts, ':');
string objectId = Str.GetValue("Object-ID", mimiParts, ':');
string contentType = Str.GetValue("Content-Type", mimiParts, ':');
if (string.IsNullOrWhiteSpace(contentId) || string.IsNullOrWhiteSpace(objectId) || string.IsNullOrWhiteSpace(contentType))
{
continue;
}
string body = mimiParts[mimiParts.Length - 1];
var filename = string.Format("{0}_{1}{2}", contentId, objectId, MimeTypeMap.GetExtension(contentType));
var decoded = System.Net.WebUtility.HtmlDecode(data);
File.WriteAllText("image_from_html_decoded_bytes" + filename, decoded);
}
Here is the method that parses the message
public class Str
{
public static string GetValue(string startWith, string[] lines, char splitter = '=')
{
foreach (var line in lines)
{
var value = line.Trim();
if (!value.StartsWith(startWith, StringComparison.CurrentCultureIgnoreCase) || !line.Contains(splitter))
{
continue;
}
return value.Split(splitter)[1].Trim();
}
return string.Empty;
}
}
Here is a screenshot showing the content of the mimiParts
variable
UPDATED 2
Based on the feedback below, I tried to use MimeKit packages instead of trying to parse the response myself. Below is how I tried to consume the response. However, I am still getting the same error as above. When writting the image file, I get image corrupted error.
var responseContentType = response.Content.Headers.GetValues("Content-Type").FirstOrDefault();
if (!ContentType.TryParse(responseContentType, out ContentType documentContentType))
{
return;
}
var stream = await response.Content.ReadAsStreamAsync();
MimeEntity entity = MimeEntity.Load(documentContentType, stream);
Multipart messages = entity as Multipart;
if (messages == null)
{
throw new Exception("Unable to cast entity to Multipart");
}
foreach (MimeEntity message in messages)
{
string contentId = message.Headers["Content-ID"];
string objectId = message.Headers["Object-ID"];
string contentType = message.Headers["Content-Type"];
if (string.IsNullOrWhiteSpace(contentId) || string.IsNullOrWhiteSpace(objectId) || string.IsNullOrWhiteSpace(contentType))
{
continue;
}
var filename = string.Format("{0}_{1}{2}", contentId, objectId, MimeTypeMap.GetExtension(contentType));
message.WriteTo(filename);
}