C# ImapX Save XML (invalid due to special character in the end) attachment

234 Views Asked by At

I have been writing a C# program to retrieve XML attachments from emails and save them to disk for further process.

if (message.Attachments != null && message.Attachments.Any())
{
    foreach (var attachment in message.Attachments)
    {
        attachment.Download();
        var fileName = String.Format("{0}-{2}{1}", Path.GetFileNameWithoutExtension(attachment.FileName), Path.GetExtension(attachment.FileName), Guid.NewGuid());
        attachment.Save(attachmentsPath, fileName);
        string contents = File.ReadAllText(attachmentsPath + "\\" + fileName);
        MessageBox.Show(String.Format("Attachment saved: {0}", fileName));
    }
}

Some of the XMLs are invalid because they are ending with the SUB character (ASCII 26) and C# pops error at this point:

attachment.Save(attachmentsPath, fileName);

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

How can I strip the XML attachments from this character before saving the XML to disk or make it ignore this special character?

0

There are 0 best solutions below