Tuesday, March 29, 2016

Let's hack! How may I keep a serialized bytes array as a string to later make an image in an MVC application?

I've had the need to do this twice now and so here is a blog posting. Let's make a class you will later throw away like so:

using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Airport.Core.Utilities
{
   public static class Stringification
   {
      public static string ForFile(string path)
      {
         byte[] bytes = File.ReadAllBytes(path);
         using (var memoryString = new MemoryStream())
         {
            using (var xmlTextWriter = new XmlTextWriter(memoryString, Encoding.UTF8))
            {
               var xmlSerializer = new XmlSerializer(bytes.GetType());
               xmlSerializer.Serialize(xmlTextWriter, bytes);
               using (var xmlTextWriterMemoryStream = (MemoryStream)
                     xmlTextWriter.BaseStream)
               {
                  UTF8Encoding utf8Encoding = new UTF8Encoding();
                  return utf8Encoding.
                        GetString(xmlTextWriterMemoryStream.ToArray()).Substring(1);
               }
            }
         }
      }
   }
}

 
 

Most of the magic above comes from this and you will ultimately make the string an image like this. Just keep the string in a static helper class somewhere. Anyhow, to see what your dummy throwaway class makes, I would just pull it up into a view and then copy and paste the XML out the what the view renders. Some applicable razor markup is:

@Stringification.ForFile("C:\\foo\\bar.jpg")

 
 

After you get the copy you may want to replace the double quotes with single quotes. There are not many of them and this act will be harmless. This act will make it a little more painless to just keep the string inside double quotes in C#.

No comments:

Post a Comment