forge

Getting the original display name for an internal name

Bil Simser posted on a problem with CAML where he mentioned reverse engineering the internal field name to the original display name that created it.  I had to do just this thing for one of migration utilities.  Here’s the code (C#):

// Fixup an internal name back to the regular way that it should be so that we can get the same
// internal name back when we create a title.
private static string FixInternalName(string internalName)
{
// Get the most common one out of the way as quickly as possible
string f1 = internalName.Replace(“_x0020_”, ” “);
int pos;
// while we have more processing to do
while ((pos = f1.IndexOf(“_”)) >= 0)
{
int chrVal;
if (pos + 6 > f1.Length)
{
chrVal = PartialEncoding(f1,pos);
}
else
{
chrVal = int.Parse(f1.Substring(pos+2, 4), System.Globalization.NumberStyles.HexNumber);
}

if (f1.Length > pos + 7)
{
// char isn’t at the end of the string
f1 = f1.Substring(0, pos) + Convert.ToChar(chrVal) + f1.Substring(pos+7);
}
else
{
f1 = f1.Substring(0, pos) + Convert.ToChar(chrVal);
}
}
return (f1);
}

private static char PartialEncoding(string fix, int pos)
{
pos += “_x”.Length;
if (fix.Length > pos)
{
string nw = String.Empty;
while(pos < fix.Length)
{
nw = nw + fix[pos];
pos++;
}
while(nw.Length < 4)
{
nw = nw + ‘0’;
}
return (Convert.ToChar(int.Parse(nw, System.Globalization.NumberStyles.HexNumber)));
}
else
{
// Not even enough to start — return a space it will get encoded
return ‘ ‘;
}
}