Nate
Nate

Reputation: 67

Determine if file is svg

Trying to validate if file is a svg by looking at the first few bytes. I know I can do this for png and other image file types but what about svg?

Maybe I have to convert bytes to string and validate using regex instead?

Upvotes: 3

Views: 5285

Answers (3)

Paul LeBeau
Paul LeBeau

Reputation: 101830

If you don't want to use an XML parser (you probably don't), then I think a 99%+ reliable method would be to read the first, say, 256 bytes. Then check for the string "<svg ", or use regex /^<svg /gm.

And/or check for the string " xmlns=\"http://www.w3.org/2000/svg\"".

From my experience working with SVG, this would catch almost all SVG files, with very few false negatives.

Upvotes: 3

Anthony Simmon
Anthony Simmon

Reputation: 1607

If performance is a concern and you don't want to read all the SVG file contents, you can use the XmlReader class to have a look at the first element:

private static bool IsSvgFile(Stream fileStream)
{
    try
    {
        using (var xmlReader = XmlReader.Create(fileStream))
        {
            return xmlReader.MoveToContent() == XmlNodeType.Element && "svg".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase);
        }
    }
    catch
    {
        return false;
    }
}

Upvotes: 5

Daniel Murillo
Daniel Murillo

Reputation: 47

You can retrieve the file using a stream and knowing that the SVG format is a XML, you can simply check it like this:

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

Upvotes: -1

Related Questions