Identify Raster (jpg, png, etc.) or svg file format from ByteString

c#, svg, wpf

Solution

The SVG file format is based on XML. Hence you could try to decode a text string from your image buffer and check if it begins with `<?xml` or `<svg`:

bool isSvg = false;

try
{
    var text = Encoding.UTF8.GetString(img);
    isSvg = text.StartsWith("<?xml ") || text.StartsWith("<svg ");
}
catch
{
}

Or maybe you just check if the first byte in the buffer is a `<`, because the raster image formats do not start with that character:

bool isSvg = img[0] == '<';

Problem

In C# (.NET FW 4.5), is there a way to understand if a bytestring holds an .svg file or any raster file? I use this routine: ``` [...] byte[] img = System.Convert.FromBase64String(res); ctrlImage = new BitmapImage(); ctrlImage.BeginInit(); MemoryStream ms = new MemoryStream(img); ctrlImage.StreamSource = ms; ctrlImage.EndInit(); ``` to convert the stream to a `BitmpatImage`, but now I need to verify if `res` contains an svg file and not a raster file. Thank you.

Original source