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?
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With