Ever since the DOS days, determining file type based on the three letter extension in its filename has been a common practice. I’d argue that it’s not a good practice, but it’s become so standard that it’s hard to avoid. It’s so common that pretty much any language in wide use has some sort of “get extension” method. C# is no exception.
Of course, having a convenient and commonly used helper method is no barrier to writing it yourself, and Andrew found this code in their application, which is meant to extract “png”, or “jpg” as the extension.
/// <summary>
/// This method returns the last three chars of the user ID using the image
/// </summary>
private string GetLastThreeCharsUID(string strImageName)
{
int intDotCount = 0;
int intDotIndex = 0;
string strSegment = “”;
string strSplit = strImageName;
//Get the last dot in the string
{
while (!(intDotCount == -1))
{
intDotCount = strSplit.IndexOf(‘.’);
if (intDotCount != -1)
{
intDotIndex = strSplit.IndexOf(‘.’);
strSegment = strSegment + strSplit.Substring(0, intDotIndex + 1);
int intLength = (strSplit.Length – (intDotIndex + 1));
strSplit = strSplit.Substring(intDotIndex + 1, intLength);
}
}
}
if (intDotIndex != -1)
{
return strImageName.Substring(intDotIndex – 3, 3);
}
else
{
return “Error”;
}
}
The name of this function, and its comments, get us confused. “the last three chars of the user ID using the image”. What? Is… their user ID an image? That can’t be, can it? This has to be a copy-paste error, where they are claiming this has something to do with user IDs but doesn’t. Right? Right?
Our approach to finding the the last . in the string is… spectacular. We check the IndexOf the dot, and if there is one, we split the string on the first dot. We stuff the first portion of the string into strSegment (which we never use), and then split on the next dot, until there are no more dots to split on.
Finally, we take a substring on what we believe to be the prefix- I think. I’m not sure why it’s intDotIndex – 3. The fact that we only grab three characters means I hope nobody uploaded a jpeg or webm file.
It’s a pretty impressive block of code, honestly. Certainly one of the hardest ways we could find to do this. It’s stuffed with so many choices that leave me scratching my head.
Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
Source: Read MoreÂ