Azure Blob Name Restriction Solution

If you’ve worked with Azure blob storage you know how awfully restricting the names are.

They can only have the following characters:

a-z

0-9

- (dash)

I may have missed a couple other characters but as you can see it is INCREDIBLY restrictive. No Unicode, no special characters, not even uppercase characters…

I came up with a pretty simple solution to this problem. Hex encode the string! This converts all the characters (Unicode works too!) into it’s 2 digit hex representation. Hex as you know only using the digits 0-9 and letters A-F. Once it is hex encoded you simple lowercase the entire string and you are good to go.

There are only 2 problems I’ve noticed with this solution. The main being that the blob and container names become REALLY hard to read by a human. The other is that all your blob and container names effectively become twice as long as their non-hex encoded string version. Blob and container names are restricted to 1024 characters, so if your design requires the names to use over 512 characters this solution isn’t for you. Without further ado, here are the 2 magic methods I use:

To encode to a hex string:

private string ConvertToHexString(string Input)
{
     string ret = string.Empty;

     foreach (char c in Input)
     {
          ret += String.Format("{0:X}", Convert.ToInt32(c));
     }

     return ret;
}

To decode from a hex string:

private string ConvertFromHexString(string Input)
{
     string ret = string.Empty;

     for (int i = 0; i < Input.Length; i += 2)
     {
          string hex = Input.Substring(i, 2);

          ret += (char)Convert.ToInt32(hex, 16);
     }

     return ret;
}
Posted in Coding Tagged with: , , , , , , , , ,

Leave a Reply