0

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?

PanosPlat
  • 940
  • 1
  • 11
  • 29
  • string sub = Encoding.UTF8.GetString(new byte[1] {0x1a}); string contents = File.ReadAllText(attachmentsPath + "\\" + fileName); contents = contents.Substring(0, contents.IndexOf(sub)); – jdweng Mar 30 '18 at 09:32
  • Unfortunately the error comes while saving the XML attachment to the disk, so it comes up earlier than your fix code :( – PanosPlat Mar 30 '18 at 09:41
  • Then put fix in attachment before saving file. I have no idea what the object type is for attachment because you are using "var" instead of the real object type. – jdweng Mar 30 '18 at 10:02
  • Thank you for your suggestion but in your fix you are getting the file from the disk. Can I somehow implement in on the attachment before needing to save it? – PanosPlat Mar 30 '18 at 10:07
  • My code is modifying a string. I can't answer how to modify attachment without know the type for attachment. – jdweng Mar 30 '18 at 10:17
  • Thanx. The attachment is an XML file. – PanosPlat Mar 30 '18 at 10:21
  • I have no idea what " attachment.Download();" is doing. I need to modify code to get the string from attachment and do not know how to do it without knowing the type? – jdweng Mar 30 '18 at 10:30

0 Answers0