Guest User

Untitled

a guest
Dec 12th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4.  
  5. namespace InfoPathAttachmentEncoding
  6. {
  7. /// <summary>
  8. /// Decodes a file attachment and saves it to a specified path.
  9. /// </summary>
  10. public class InfoPathAttachmentDecoder
  11. {
  12. private const int SP1Header_Size = 20;
  13. private const int FIXED_HEADER = 16;
  14. private int fileSize;
  15. private int attachmentNameLength;
  16. private string attachmentName;
  17. private byte[] decodedAttachment;
  18.  
  19. /// <summary>
  20. /// Accepts the Base64 encoded string
  21. /// that is the attachment.
  22. /// </summary>
  23. public InfoPathAttachmentDecoder(string theBase64EncodedString)
  24. {
  25. byte [] theData = Convert.FromBase64String(theBase64EncodedString);
  26. using(MemoryStream ms = new MemoryStream(theData))
  27. {
  28. BinaryReader theReader = new BinaryReader(ms);
  29. DecodeAttachment(theReader);
  30. }
  31. }
  32.  
  33. private void DecodeAttachment(BinaryReader theReader)
  34. {
  35. //Position the reader to obtain the file size.
  36. byte[] headerData = new byte[FIXED_HEADER];
  37. headerData = theReader.ReadBytes(headerData.Length);
  38. fileSize = (int)theReader.ReadUInt32();
  39. attachmentNameLength = (int)theReader.ReadUInt32() * 2;
  40. byte[] fileNameBytes = theReader.ReadBytes(attachmentNameLength);
  41. //InfoPath uses UTF8 encoding.
  42. Encoding enc = Encoding.Unicode;
  43. attachmentName = enc.GetString(fileNameBytes, 0, attachmentNameLength - 2);
  44. decodedAttachment = theReader.ReadBytes(fileSize);
  45. }
  46.  
  47. public void SaveAttachment(string saveLocation)
  48. {
  49. string fullFileName = saveLocation;
  50. if (!fullFileName.EndsWith(Path.DirectorySeparatorChar.ToString()))
  51. {
  52. fullFileName += Path.DirectorySeparatorChar;
  53. }
  54. fullFileName += attachmentName;
  55. if(File.Exists(fullFileName))
  56. File.Delete(fullFileName);
  57. FileStream fs = new FileStream(fullFileName, FileMode.CreateNew);
  58. BinaryWriter bw = new BinaryWriter(fs);
  59. bw.Write(decodedAttachment);
  60. bw.Close();
  61. fs.Close();
  62. }
  63.  
  64. public string Filename
  65. {
  66. get{ return attachmentName; }
  67. }
  68.  
  69. public byte[] DecodedAttachment
  70. {
  71. get{ return decodedAttachment; }
  72. }
  73. }
  74. }
Add Comment
Please, Sign In to add comment