From 32dff4350afae1b4df232e4acf404ac06eb6b3c8 Mon Sep 17 00:00:00 2001 From: Roberto Basile Date: Thu, 24 Aug 2023 17:08:44 -0400 Subject: [PATCH] Added method to check if file is supported instead of waiting for exception --- src/TaglibSharp/File.cs | 44 ++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/TaglibSharp/File.cs b/src/TaglibSharp/File.cs index 40f691c69..a9b1d8147 100644 --- a/src/TaglibSharp/File.cs +++ b/src/TaglibSharp/File.cs @@ -1235,6 +1235,37 @@ public static File Create (string path, string mimetype, ReadStyle propertiesSty return Create (new LocalFileAbstraction (path), mimetype, propertiesStyle); } + /// + /// Returns true if the file is supported + /// + /// The file path + /// True if supported, false otherwise + public static bool IsSupportedFile (string path) + { + var abstraction = new LocalFileAbstraction (path); + + return IsSupportedFile (abstraction); + } + + private static bool IsSupportedFile(IFileAbstraction abstraction) + { + string mimetype = GetMimeType (abstraction); + + return FileTypes.AvailableTypes.ContainsKey (mimetype); + } + + private static string GetMimeType (IFileAbstraction abstraction) + { + string ext = string.Empty; + + int index = abstraction.Name.LastIndexOf (".") + 1; + + if (index >= 1 && index < abstraction.Name.Length) + ext = abstraction.Name.Substring (index, abstraction.Name.Length - index); + + return $"taglib/{ext.ToLower (CultureInfo.InvariantCulture)}"; + } + /// /// Creates a new instance of a subclass /// for a specified file abstraction, mime-type, and read @@ -1269,16 +1300,7 @@ public static File Create (string path, string mimetype, ReadStyle propertiesSty /// public static File Create (IFileAbstraction abstraction, string mimetype, ReadStyle propertiesStyle) { - if (mimetype == null) { - string ext = string.Empty; - - int index = abstraction.Name.LastIndexOf (".") + 1; - - if (index >= 1 && index < abstraction.Name.Length) - ext = abstraction.Name.Substring (index, abstraction.Name.Length - index); - - mimetype = "taglib/" + ext.ToLower (CultureInfo.InvariantCulture); - } + mimetype ??= GetMimeType (abstraction); foreach (var resolver in file_type_resolvers) { var file = resolver (abstraction, mimetype, propertiesStyle); @@ -1287,7 +1309,7 @@ public static File Create (IFileAbstraction abstraction, string mimetype, ReadSt return file; } - if (!FileTypes.AvailableTypes.ContainsKey (mimetype)) + if (!IsSupportedFile(abstraction)) throw new UnsupportedFormatException ( string.Format (CultureInfo.InvariantCulture, "{0} ({1})", abstraction.Name, mimetype));