Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if file is svg

Tags:

c#

image

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?

like image 578
Nate Avatar asked Nov 29 '25 08:11

Nate


2 Answers

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;
    }
}
like image 113
Anthony Simmon Avatar answered Dec 01 '25 22:12

Anthony Simmon


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.

like image 25
Paul LeBeau Avatar answered Dec 01 '25 21:12

Paul LeBeau